c# – 将T转换为bool,反之亦然
发布时间:2020-12-15 08:39:59 所属栏目:百科 来源:网络整理
导读:我有以下扩展方法,以便字符串能够执行此操作(“true”).作为 bool(false) 特别是对于布尔值,它将使用AsBool()进行一些自定义转换. 不知怎的,我不能从T转向Bool,反之亦然.我使用下面的代码工作,但它似乎有点矫枉过正. 这是关于这一行: (T)Convert.ChangeType
|
我有以下扩展方法,以便字符串能够执行此操作(“true”).作为< bool>(false)
特别是对于布尔值,它将使用AsBool()进行一些自定义转换. 不知怎的,我不能从T转向Bool,反之亦然.我使用下面的代码工作,但它似乎有点矫枉过正. 这是关于这一行: 我错过了什么或者这是最短的路要走? public static T As<T>(this string value)
{
return As<T>(value,default(T));
}
public static T As<T>(this string value,T fallbackValue)
{
if (typeof(T) == typeof(bool))
{
return (T)Convert.ChangeType(AsBool(value,typeof(T));
}
T result = default(T);
if (String.IsNullOrEmpty(value))
return fallbackValue;
try
{
var underlyingType = Nullable.GetUnderlyingType(typeof(T));
if (underlyingType == null)
result = (T)Convert.ChangeType(value,typeof(T));
else if (underlyingType == typeof(bool))
result = (T)Convert.ChangeType(AsBool(value,typeof(T));
else
result = (T)Convert.ChangeType(value,underlyingType);
}
finally { }
return result;
}
public static bool AsBool(this string value)
{
return AsBool(value,false);
}
public static bool AsBool(this string value,bool fallbackValue)
{
if (String.IsNullOrEmpty(value))
return fallbackValue;
switch (value.ToLower())
{
case "1":
case "t":
case "true":
return true;
case "0":
case "f":
case "false":
return false;
default:
return fallbackValue;
}
}
解决方法
您可以将其强制转换为object,然后转换为T:
if (typeof(T) == typeof(bool))
{
return (T)(object)AsBool(value,Convert.ToBoolean(fallbackValue));
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
