gpt4 book ai didi

c# - 将 Nullable 转换为通用类型

转载 作者:行者123 更新时间:2023-11-30 13:32:59 25 4
gpt4 key购买 nike

假设这个方法:

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

}

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

Invalid cast from 'System.Boolean' to 'System.Nullable`1[[System.Boolean, 
mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.

我不明白哪里出了问题 我不用Boolean 我用Boolean?

这是我的电话:

Product.IsAllow= GetParameterValue<Boolean?>("IsAllow");

那么你对此有何看法?

最佳答案

你可以使用

return (T)(object)istrue;

不过我根本不会使用这种代码。只需创建一个专门解析每种数据类型的方法(例如 bool?GetBooleanParameter(string name))。此处的泛型不会给您带来任何好处,只会使代码更加繁琐。

关于c# - 将 Nullable<Boolean> 转换为通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10266220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com