微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 将T转换为bool,反之亦然

我有以下扩展方法,以便字符串能够执行此操作(“true”).作为< bool>(false)
特别是对于布尔值,它将使用AsBool()进行一些自定义转换.
不知怎的,我不能从T转向Bool,反之亦然.我使用下面的代码工作,但它似乎有点矫枉过正.

这是关于这一行:
(T)Convert.ChangeType(AsBool(value,Convert.ToBoolean(fallbackValue)),typeof(T))
我宁愿使用以下内容,但它不会编译:
(T)AsBool(value,(bool)fallbackValue),typeof(T))

我错过了什么或者这是最短的路要走?

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));
}

原文地址:https://www.jb51.cc/csharp/244412.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐