10

これを実行できるようにするために、文字列に対して次の拡張メソッドがあります。("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;
        }
    }
4

1 に答える 1

14

あなたはそれをにキャストしてobjectからT:にキャストすることができます

if (typeof(T) == typeof(bool))
{
  return (T)(object)AsBool(value, Convert.ToBoolean(fallbackValue));
}
于 2012-08-24T13:59:20.190 に答える