Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/symfony/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 转换为空值<;布尔值>;到泛型类型_C#_Generics_Exception_C# 4.0_Nullable - Fatal编程技术网

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;