[英]Detecting nullable types in C#
我有一个这样定义的方法:
public bool IsValid(string propertyName, object propertyValue)
{
bool isValid = true;
// Validate property based on type here
return isValid;
}
我想做类似的事情:
if (propertyValue is bool?)
{
// Ensure that the property is true
}
我的挑战是,我不确定如何检测我的 propertyValue 是否为可为空的布尔值。 有人可以告诉我该怎么做吗?
谢谢!
propertyValue
的值永远不能是Nullable<bool>
。 由于propertyValue
的类型是object
,任何值类型都将被装箱......如果你装箱一个可为空的值类型值,它成为 null 引用,或底层不可为空类型的装箱值。
换句话说,您需要在不依赖值的情况下找到类型......如果您可以为我们提供更多关于您想要实现的目标的背景信息,我们可能会为您提供更多帮助。
您可能需要为此使用 generics 但我认为您可以检查 propertyvalue 的可为空的基础类型,如果它是 bool,它就是一个可为空的 bool。
Type fieldType = Nullable.GetUnderlyingType(typeof(propertyvalue));
if (object.ReferenceEquals(fieldType, typeof(bool))) {
return true;
}
否则尝试使用泛型
public bool IsValid<T>(T propertyvalue)
{
Type fieldType = Nullable.GetUnderlyingType(typeof(T));
if (object.ReferenceEquals(fieldType, typeof(bool))) {
return true;
}
return false;
}
这可能是一个长镜头,但是您可以使用 generics 和方法重载让编译器为您解决这个问题吗?
public bool IsValid<T>(string propertyName, T propertyValue)
{
// ...
}
public bool IsValid<T>(string propertyName, T? propertyValue) where T : struct
{
// ...
}
另一个想法:您的代码是否试图通过 object 上的每个属性值来 go? 如果是这样,您可以使用反射来遍历属性,并以这种方式获取它们的类型。
正如Denis在他的回答中建议的那样使用Nullable.GetUnderlyingType
可以解决使用重载的需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.