【问题标题】:Generic cast type to primitive通用类型转换为原始类型
【发布时间】:2011-02-13 08:23:44
【问题描述】:

有没有办法做到以下几点?想象一个通用的结果包装类。你有一个类型和一个相关的错误列表。当没有结果返回给用户时,我们将使用布尔值表示成功失败。我想创建一个接受错误列表的构造函数,如果列表为 null 或计数为 0,AND 类型是 bool/Boolean 我想将其设置为 true....

看似简单,但实际上不可能。

public class Result<T>{
    private T valueObject { get;set;}
    private List<Error> errors{ get;set;}

    public Result(T valueObj, List<Error> errorList){
        this.valueObject = valueObj;
        this.errors = errorList;

    }

    public Result(List<Error> errors)
    {
        this.valueObject = default(ReturnType);

        if (valueObject is Boolean)
        {
           //Wont work compile
           //(valueObject as Boolean) = ((errors == null) || errors.Count == 0);

             //Compiles but detaches reference 
             //bool temp = ((bool)(valueObject as object)) ;
             //temp = ((errors == null) || errors.Count == 0);

        }
        this.errors = errors;
    }

}

}

我错过了一些简单的东西吗?总的来说,我宁愿不反思。

【问题讨论】:

  • default(ReturnType) 是指default(T)
  • 您是否考虑过使用 Nullable 来表示值?
  • 我的意思是默认(T),发帖时搞砸了。
  • 而且我真的不需要一个可以为空的类型,但我确实认识到这会让我使用“as”运算符。

标签: c# generics .net-3.5


【解决方案1】:

在转换为泛型 T 之前将其转换为对象,应该可以正常工作:

    if (valueObject is Boolean)
    {
         this.valueObject = (T)(object)((errors == null) || errors.Count == 0);
    }

【讨论】:

    【解决方案2】:
    public Result(List<Error> errors)
    {
        valueObject = default(T);
        if (typeof(T) == typeof(bool)) // no need to check the object, we know the generic type
        {
           if (errors == null || errors.Count == 0)
               valueObject = (T)(object)true; // a 'magic' cast to make it compile
        }
        this.errors = errors;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-16
      • 2013-06-19
      • 2021-06-16
      • 1970-01-01
      • 2013-01-12
      相关资源
      最近更新 更多