将Nullable <Boolean>转换为Generic类型

Sae*_*eid 3 c# generics nullable exception c#-4.0

假设这个方法:

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

}
Run Code Online (Sandbox Code Playgroud)

所以这个方法总是在返回行中引发异常:

Invalid cast from 'System.Boolean' to 'System.Nullable`1[[System.Boolean, 
mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.
Run Code Online (Sandbox Code Playgroud)

我不明白问题出在哪里,我不使用Boolean我用Boolean?

这是我的电话:

Product.IsAllow= GetParameterValue<Boolean?>("IsAllow");
Run Code Online (Sandbox Code Playgroud)

那你对此有什么看法?

Eli*_*bel 8

您可以使用

return (T)(object)istrue;
Run Code Online (Sandbox Code Playgroud)

我根本不会使用这种代码.只需创建一个专门解析每种数据类型的方法(例如bool? GetBooleanParameter(string name)).你没有在这里使用泛型获得任何东西,只是使代码更麻烦.