我正在编写一种方法来在控制台上为用户查询某些内容并获得他的答案......像这样:
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
始终是int
或double
...
有什么好的方法吗?
提前致谢!
最佳答案
使用 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/