c# - 如何在 C# 上将内置结构转换为参数类型 T?

标签 c# casting

我正在编写一种方法来在控制台上为用户查询某些内容并获得他的答案......像这样:

static T query<T>(String queryTxt)
    {
        Console.Write("{0} = ", queryTxt);
        T result;
        while (true)
        {
            try
            {
                result = // here should go the type casting of Console.ReadLine();
            }
            catch (FormatException e)
            {
                Console.WriteLine("Exception: {0};\r\nSource: {1}", e.Message, e.Source);
                continue;
            }
            break;
        }
        return result;
    }

简而言之,此方法应不断询问queryTxt 的值,其中T 始终是intdouble...

有什么好的方法吗?

提前致谢!

最佳答案

使用 type converters .

public static T Query<T>() {
    var converter = TypeDescriptor.GetConverter(typeof (T));
    if (!converter.CanConvertFrom(typeof(String)))
        throw new NotSupportedException("Can not parse " + typeof(T).Name + "from String.");

    var input = Console.ReadLine();

    while (true) {
        try {
            // TODO: Use ConvertFromInvariantString depending on culture.
            return (T)converter.ConvertFromString(input);
        } catch (Exception ex) {
            // ...
        }
    }
}

关于c# - 如何在 C# 上将内置结构转换为参数类型 T?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4610062/

相关文章:

其他库中类型之间的 C++ 转换运算符

c# - 我可以通过 Type 变量而不是显式类型来转换类的实例吗?

java - 为什么列表列表 <? super E> 是列表 <?扩展列表 <? super E>> 但不是 List<List<? super E>>

c# - 在 dotnetcf 2.0 (WM6) 中启动拨号程序

c# 使用 SET 有什么意义?

c# - EF lambda : The Include path expression must refer to a navigation property

c# - 检查 Func<> 调用中是否被零除

c# - 无法确定文本框 KeyPress 事件的 '.' keychar

c++ - 在 C++ 中将指向前向声明的类的指针转换为其真正的基类是否安全?

c - 提取交错 float 据