本文介绍了在C#中将string.Empty转换为(generic)T?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个实用程序方法,它从旧的 .INI 配置类型文件中返回一个强类型值,并带有签名
内部静态T GetIniSetting< T>(string config,string key,T defVal = default(T))我希望字符串是特殊的,因为我希望 defaultValue 的默认值为 string.Empty ,而不是默认(字符串)(即null),在编码器未指定默认值的情况下。
if(cantFindValueInIniFile == true) { if((typeof(T)== typeof(string))& &(defaultValue == null)) { // ***此处需要的代码 - 无法将字符串转换为< T> *** return(T)string.Empty; } return defaultValue; }我已经试过硬铸造了,作为
解决方案'hacky'的方式:
return(T)(object)string.Empty;注意:
I have a utility method which returns a strongly typed value from an old .INI configuration type file, with the signature
internal static T GetIniSetting<T>(string config, string key, T defVal = default(T))I want strings to be special, in that I would like the default value for defaultValue to be string.Empty, not default(string) (i.e. null), in the case when the coder hasn't specified a default value.
if (cantFindValueInIniFile == true) { if ((typeof(T) == typeof(string)) && (defaultValue == null)) { // *** Code needed here - Cannot convert string to <T>*** return (T)string.Empty; } return defaultValue; }I've tried hard casting, and the as keyword, to no avail.
解决方案The 'hacky' way:
return (T)(object)string.Empty;Notes:
- Pretty safe as you have check pre-conditions.
- Performance penalty unnoticeable on reference types.
更多推荐
在C#中将string.Empty转换为(generic)T?
发布评论