Cast string.Empty to (generic) T in C#?

▼魔方 西西 提交于 2020-01-01 09:22:15

问题


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.


回答1:


The 'hacky' way:

return (T)(object)string.Empty; 

Notes:

  • Pretty safe as you have check pre-conditions.
  • Performance penalty unnoticeable on reference types.



回答2:


You have to do it like this: (T)(object)(string.Empty).

Also, a minor optimization is to store this in a static readonly string field so that you don't have to do the casts but one time per generic parameter (instead of per method call)




回答3:


If I'm not mistaken, the last parameter in GetIniSetting is optional, and you will get default(string) only if you don't provide anything for it. So to use string.Empty as a default string value make the call like:

string value = GetIniSetting<string>(config, key, string.Empty);


来源:https://stackoverflow.com/questions/10943202/cast-string-empty-to-generic-t-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!