首页 > 解决方案 > 如何创建多态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) 我不知道在括号里放什么。

标签: c#

解决方案


我假设一些事情,因为它们不清楚:

  • 自从我在您的代码中看到以来,您的意思是数据类型而不是日期类型,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!

推荐阅读