在C#中将string.Empty转换为(generic)T?

编程入门 行业动态 更新时间:2024-10-22 20:35:27
本文介绍了在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?

本文发布于:2023-10-16 16:38:20,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   中将   Empty   string   generic

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!