【发布时间】:2013-05-26 22:26:36
【问题描述】:
我为以下Nullable类型编写了重载的静态TryParse方法:int?、short?、long?、double?、DateTime?、decimal?、float?、@98764 @、byte? 和 char?。下面是一些实现:
protected static bool TryParse(string input, out int? value)
{
int outValue;
bool result = Int32.TryParse(input, out outValue);
value = outValue;
return result;
}
protected static bool TryParse(string input, out short? value)
{
short outValue;
bool result = Int16.TryParse(input, out outValue);
value = outValue;
return result;
}
protected static bool TryParse(string input, out long? value)
{
long outValue;
bool result = Int64.TryParse(input, out outValue);
value = outValue;
return result;
}
每个方法的逻辑都是相同的,只是它们使用不同的类型。难道不能使用泛型,这样我就不需要那么多冗余代码了吗?签名看起来像这样:
bool TryParse<T>(string input, out T value);
谢谢
【问题讨论】:
-
泛型方法不适用的一个原因是并非所有
structs 都有TryParse方法,但是您不能使用泛型约束在编译时只允许兼容类型。 -
顺便说一下,您在提议的方法签名中缺少第二个
T之后的?。
标签: c# .net parsing generics type-conversion