How to cast a built-in struct to a parameter type T on C#?
I'm programming a method to query something for the user on the Console and getting his answer... Something like this:
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;
}
In short, this method should keep asking for the value of queryTxt
, where T
is always int
or double
...
Any good way to do this?
Thanks in advance!
Using 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) {
// ...
}
}
}
if its always int or double work with double.Parse and it'll always work.
One way to generalize it is to pass conversion function as delegate. Something like:
T query<T>(string text, Func<string, T> converter)
{... result = converter(Console.Readline())...}
query("foo", s=>Int.Parse(s));
For more generic approach - read "Generalized Type Conversion " http://msdn.microsoft.com/en-us/library/yy580hbd.aspx and related articles.
精彩评论