将T转换为bool,反之亦然

Sil*_*ind 7 c# casting type-conversion

我有以下扩展方法,使字符串能够做到这一点("true").As<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,
                                                Convert.ToBoolean(fallbackValue)),
                                                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,
                                                Convert.ToBoolean(fallbackValue)),
                                                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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Ste*_*fan 10

你可以把它投射到object然后T:

if (typeof(T) == typeof(bool))
{
  return (T)(object)AsBool(value, Convert.ToBoolean(fallbackValue));
}
Run Code Online (Sandbox Code Playgroud)

  • 这样看起来更干净:).我不能直接投的原因是什么? (4认同)