有没有办法在下面做?想象一下通用的结果包装类。您有类型和关联错误列表的位置。当没有结果返回给用户时,我们将使用布尔值来表示成功失败。我想创建一个接收错误列表的构造函数,如果列表为null或计数0, AND ,则类型为bool / Boolean我想将其设置为true .... / p>
看似简单,但令人惊讶的是不可能。
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;
}
}
}
我错过了一些简单的东西吗?总的来说,我更愿意在没有反思的情况下这样做。
答案 0 :(得分:6)
在转换为通用T之前将其强制转换为对象,应该可以正常工作:
if (valueObject is Boolean)
{
this.valueObject = (T)(object)((errors == null) || errors.Count == 0);
}
答案 1 :(得分:0)
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;
}