[英]Can c# know the type of an object when it's value is null?
While making some validation, I can across this situation在进行一些验证时,我可以跨越这种情况
public override bool IsValid(object value)
{
if(!(value is IFileUploadInfo) && !(value is IEnumerable<IFileUploadInfo>))
throw new ArgumentException($"Cannot use {nameof(FileValidationAttribute)} in a property that isn't of type {nameof(IFileUploadInfo)} or {nameof(IEnumerable<IFileUploadInfo>)}");
// rest ...
}
Where I need to test if a object
is of the type that I want, but if value
is null
, will c# know the type of that object even when it's null
? Where I need to test if a object
is of the type that I want, but if value
is null
, will c# know the type of that object even when it's null
?
You can't.你不能。 Passing with object
in erases what the type was at compile time.使用object
传递会擦除编译时的类型。 Hence you have to do some pattern matching or casting to get it back out.因此,您必须进行一些模式匹配或强制转换才能将其恢复。 Hence, null
doesn't carry any type information with it.因此, null
不携带任何类型信息。
You could make the method generic and then you could get what the type was.您可以使该方法通用,然后您可以得到类型是什么。
public override bool IsValid<T>(T value)
{
Type t = typeof(T);
...
// rest of code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.