Stu*_*tLC 8 c# generics casting
我有一个实用程序方法,它.INI使用签名从旧配置类型文件返回强类型值
internal static T GetIniSetting<T>(string config, string key, T defVal = default(T))
Run Code Online (Sandbox Code Playgroud)
我希望字符串是特殊的,因为在编码器没有指定默认值的情况下,我希望defaultValue的默认值是string.Empty,而不是default(string)(即为null).
if (cantFindValueInIniFile == true)
{
if ((typeof(T) == typeof(string)) && (defaultValue == null))
{
// *** Code needed here - Cannot convert string to <T>***
return (T)string.Empty;
}
return defaultValue;
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试过强制转换和as关键字,但无济于事.
lep*_*pie 12
'hacky'方式:
return (T)(object)string.Empty;
Run Code Online (Sandbox Code Playgroud)
笔记:
你必须这样做:(T)(object)(string.Empty).
此外,次要优化是将其存储在静态只读字符串字段中,这样您就不必每次使用一次参数(而不是每个方法调用)进行一次转换