[英]Generic cast type to primitive
Is there a way to do the below? 有没有办法在下面做? Imagine a generic result wrapper class. 想象一下通用的结果包装类。 Where you have a type and an associated error list. 您有类型和关联错误列表的位置。 When there is no result to return to the user we will use boolean to indicate success failure. 当没有结果返回给用户时,我们将使用布尔值来表示成功失败。 I want to create a constructor that takes in an error list, and if the list is null or count 0, AND the type is a bool/Boolean i want to set it to true.... 我想创建一个构造函数中的错误列表,如果该列表为空或计数0, 并且类型是BOOL /布尔我想将它设置为true ....
Seemingly simple, but amazingly not possible. 看似简单,但令人惊讶的是不可能。
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;
}
}
} }
Am I missing something simple? 我错过了一些简单的事吗? And in general I would prefer to do it without reflection. 总的来说,我更愿意在没有反思的情况下这样做。
Casting it to object before to cast to generic T, should work well: 在转换为通用T之前将其强制转换为对象,应该可以正常工作:
if (valueObject is Boolean)
{
this.valueObject = (T)(object)((errors == null) || errors.Count == 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.