C# 转换为空值<;布尔值>;到泛型类型
假设此方法:C# 转换为空值<;布尔值>;到泛型类型,c#,generics,exception,c#-4.0,nullable,C#,Generics,Exception,C# 4.0,Nullable,假设此方法: public T GetParameterValue<T>(string ParamName) { if(typeof(T) == typeof(Boolean?) && Request.QueryString.AllKeys.Contains(ParamName)) { Boolean? istrue = null; if(Request.QueryString.GetValues(
public T GetParameterValue<T>(string ParamName) {
if(typeof(T) == typeof(Boolean?) && Request.QueryString.AllKeys.Contains(ParamName)) {
Boolean? istrue = null;
if(Request.QueryString.GetValues(ParamName).FirstOrDefault() == "1")
istrue = true;
else if(Request.QueryString.GetValues(ParamName).FirstOrDefault() == "0")
istrue = false;
return (T)Convert.ChangeType(istrue, typeof(T));
}
//Other types implementation
}
我不明白哪里出了问题,我没有使用Boolean
我使用Boolean?
这是我的电话线:
Product.IsAllow= GetParameterValue<Boolean?>("IsAllow");
Product.IsAllow=GetParameterValue(“IsAllow”);
那么你的想法是什么呢?你可以使用
return (T)(object)istrue;
不过,我根本不会使用这种代码。只需创建一个专门解析每种数据类型的方法(例如bool?GetBooleanParameter(字符串名称)
)。这里的泛型并没有带来任何好处,只会让代码变得更麻烦
我不明白哪里出了问题,我没有使用Boolean
我使用Boolean?
是的,但是在ChangeType
看到它之前,您不知不觉地将其转换为Boolean
第一个参数的类型为对象
。当可为空的值类型(在本例中为bool?
)转换为object
)时,您将获得null
,或不可为空类型的实例。因此,当ChangeType
看到它时,它不再是一个可为空的布尔值
真正的问题是,
Converter
不支持可空类型。最好是在特殊情况下,如果类型为T?
,检查参数是否为null或空字符串,如果是,则返回null,否则,转换为T
。或者不要在不是最佳方式的地方使用转换器。不是答案,但为什么是有条件的。只需执行isTrue=Request.QueryString.GetValues(ParamName).FirstOrDefault()=“1”
@JohnFx:还有第三个状态,其中返回值可能为null<代码>!=“1”
不一定意味着==“0”
。如果t作为布尔值传递,而不是布尔值传递,这是否适用/工作相同?我正在测试它,它会产生相同的结果。
return (T)(object)istrue;