c# - 如何创建多态indate类型c#
问题描述
我想编写一个函数,让编码员编写他想要插入到程序中的日期类型,然后该函数检查是否可以将某个输入转换为这种类型。问题是,我不知道如何让编码器选择日期类型。
我尝试了 typeof valuetype 等。
public object checkvalu()//(type t)I added the empty brackets just for the code to run
{
//t output; This is the original code.
int output;//Not found in original code, I just added the code to run
string input = null;
bool b =int.TryParse(input, out output);
while (b != true)
{
Console.WriteLine("the valu is incorct. enter new valu");
input = (Console.ReadLine());
b = int.TryParse(input, out output);
}
output = Convert.ToInt32(input);
return output;
}
public object checkvalu(type t) 我不知道在括号里放什么。
解决方案
我假设一些事情,因为它们不清楚:
- 自从我在您的代码中看到以来,您的意思是数据类型而不是日期类型,
type t
- 不清楚用户应该在哪里输入他想要的类型,我只会写函数。
所以这里的事情:
public static object CheckValue(string type)
{
// Get the type from string
Type t = Type.GetType(type);
// Used in the loop
bool isConvertable = false;
// Initialize object
object convertInput = null;
Console.Write("Enter a value: ");
while (isConvertable == false)
{
try
{
string input = Console.ReadLine();
convertInput = Convert.ChangeType(input, t);
isConvertable = true;
}
catch (Exception)
{
// If the conversion throw an exception, it means that it has an incorrect type
Console.Write("The value is incorrect, enter new value: ");
}
}
// Just for output purpose
Console.WriteLine("Value has the correct type!");
return convertInput;
}
当你这样称呼它时:
CheckValue("System.Int32");
这将是输出:
Enter a value: this is a string
The value is incorrect, enter new value: 10
Value has the correct type!
推荐阅读
- docker - Docker - 如何通过 jwilder nginx-proxy 公开端口?
- c# - 如何从代码运行 Azure DevOps 管道?
- c++ - 为什么循环没有中断,并且 if 条件也没有按预期工作?
- reactjs - 登录后我的自定义路由无法正常工作
- php - 在 yii 框架中调用未定义的方法 stdClass::save()
- navigation - 想要在渐进式 Web 应用程序中使用 Navigation API 并想要添加自定义语音消息
- c# - Unity PlayMaker - 找不到动作脚本
- sql - MSSql - 选择语句不适用于所有列
- git - Git如何查看从哪个分支创建的分支
- wpf - 如何将 treeViewItem.name 设置为 1.1