0

How can I make this function reliably cast sourceValue to type T where sourceValue is bool and T is int?

public static T ConvertTo<T>(Object sourceValue)
{
  // IF IS OF THE SAME TYPE --> RETURN IMMEDIATELY
  if (sourceValue is T)
    return (T) sourceValue;

  var val = ConvertTo(sourceValue, typeof (T));
  return (T) val; 
}

Currently, this throws an InvalidCastException when trying to convert false to 0 and true to 1. The types are not predefined, which is why generics must be used here. However, the only case where it fails is when T:Int32 and sourceValue:Boolean.

4

5 回答 5

4

Is false=0 and true=1? Maybe in other languages, but here the cast makes no sense. If you really need this, I think it's a special case.

于 2009-09-11T21:18:23.583 回答
2

我认为将 bool 转换为 int 是未定义的。但是,我认为在您的函数中明确写出该特殊情况也不合适,否则您的函数与 .NET 隐式处理整数和布尔值的方式不一致。

你最好写:

int value = someFlag ? 1 : 0;
于 2009-09-11T21:27:00.520 回答
1

不完全确定您要做什么,但 .net 确实支持转换boolint

Convert.ToInt32(true);

它也可以取一个object, 并判断它是否是一个bool.
另请参阅:Convert.ToInt32(bool)Convert.ToInt32(Object)

于 2009-09-11T21:39:19.087 回答
0

作为马克自己的回答的后续行动。我认为这是一个不错的解决方案:

        protected Nullable<T> ConvertTo<T>(Object sourceValue) where T : struct, IComparable
    {
        if (sourceValue is T)
            return (T)sourceValue;

        if (sourceValue == null)
        {
            return null;
        }
        try
        {
            var val = Convert.ChangeType(sourceValue, typeof(T));
            return (T)val;
        }
        catch (FormatException)
        {
            return null;
        }

    }
于 2014-07-03T10:56:15.347 回答
-1

我需要一个高度通用的解决方案。这是我能想到的最好的:

公共静态 T ConvertTo(对象源值)
    {
      // 如果是相同类型 --> 立即返回
      如果(源值是 T)
        返回 (T) 源值;

      var val = ConvertTo(sourceValue, typeof (T));

      // 特殊情况:将 bool(sourceValue) 转换为 int(T)
      如果(val 是布尔值)
      {
        var b = (bool) val;
        如果 (b)
          返回(T)(对象)1;// 如果 val 为真,则返回 1

        返回(T)(对象)0;
      }

      返回 (T) 值;
    }
于 2009-09-11T21:38:21.040 回答