har*_*sky 13 c# generic-method optional-arguments
是否有可能写出类似的结构?
我想以某种方式设置类型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;
}
Run Code Online (Sandbox Code Playgroud)
另外,我发现以下链接:
通用类型转换FROM字符串
我认为,此代码必须工作
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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果您知道 T 将有一个无参数构造函数,您可以像这样使用 new T() :
private T GetNumericVal<T>(string sColName, T defVal = new T()) where T : new()
Run Code Online (Sandbox Code Playgroud)
否则你可以使用 default(T)
private T GetNumericVal<T>(string sColName, T defVal = default(T))
Run Code Online (Sandbox Code Playgroud)