简体   繁体   English

当 c# 的值为 null 时,c# 可以知道 object 的类型吗?

[英]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
}

No, you can't obtain type information from null with type check.不,您无法通过类型检查从null获取类型信息。

MyClass mc = null;
object obj = mc;
Console.WriteLine(obj is MyClass); // prints "False"

Docs are clear about it: 文档对此很清楚:

The is expression is true if expr isn't null, and...如果 expr 不是 null,则is表达式为真,并且...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C#\\ Dynamic \\如果动态var为null(对象类型)或零(值类型),我是否可以签入一条语句 - C# \ Dynamic \ can I check in one statement if dynamic var is null (object type) or zero (value type) 获取C#中动态对象的属性类型(即使value为null) - Get property type of dynamic object in C# (even when value is null) 我可以在C#/ WPF中获取绑定对象的Type()(即使绑定值为null)? - Can I get the Type() of a bound object in C#/WPF (even if the bound value is null)? C#6 null传播当object为null时设置的值 - C# 6 null propagation what value is set when object is null 如何在C#中检查可为空类型的空值? - How can check null value in nullable type in C#? 当存在显式引用类型时,C# 可以推断 Object 构造上的通用参数吗? - Can C# Infer the Generic Parameter on Object Construction when there's an Explicit Reference Type? 在c#值类型或引用类型中为null - Is null in c# value type or reference type 我可以在C#中将对象强制转换为其通用类型吗? - can I cast an object to it's generic type in C#? C# 想知道是否有任何枚举类型仅在限制范围内重复其值 - C# Want to know is there any enum type that repeats it's value only in the limit 如果没有System.Web.dll,C#Library Code如何知道它的托管应用程序类型? - How can C# Library Code know it's hosting application type without System.Web.dll?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM