是否可以编写类似的结构?
我想以某种方式为 T 类型的参数设置默认值。
private T GetNumericVal<T>(string sColName, T defVal = 0)
{
string sVal = GetStrVal(sColName);
T nRes;
if (!T.TryParse(sVal, out nRes))
return defVal;
return nRes;
}
此外,我发现以下链接:
Generic type conversion FROM string
I think, this code must work
private T GetNumericVal<T>(string sColName, T defVal = default(T)) where T : IConvertible
{
string sVal = GetStrVal(sColName);
try
{
return (T)Convert.ChangeType(sVal, typeof(T));
}
catch (FormatException)
{
return defVal;
}
}