在C#中将string.Empty转换为(generic)T? [英] Cast string.Empty to (generic) T in C#?

查看:194
本文介绍了在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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆