简体   繁体   English

获取对象引用未设置为对象实例的空引用对象的类型

[英]Get type of null reference object for Object reference not set to an instance of an object

Ever since I started programming this question has been annoying me, not "where is my code null" but specifically is there any way to get the type of the object that is null from the exception? 自从我开始编程以来,这个问题一直困扰着我,而不是“我的代码为空”在哪里,而是特别有没有办法从异常中获取为空的对象的类型?

Failing that, can anyone provide a blog post or msdn article that explains the reason why the .NET Framework doesn't (or can't) provide these details? 失败了,谁能提供一篇博客文章或msdn文章来解释.NET Framework不提供(或不提供)这些详细信息的原因?

Um... Because it's null. 嗯...因为它为空。

In C#, a reference type is a pointer to something. 在C#中,引用类型是指向某物的指针。 A null pointer isn't pointing to anything. 空指针不指向任何东西。 You are asking, "What type of thing would this point to if it was pointing to something". 您在问,“如果指向某事物,它将指向哪种类型的事物”。 That's sort of like getting a blank sheet of paper, and asking, "What would this say if it had something written on it?" 这就像拿一张白纸,然后问:“如果上面写着什么,这会怎么说呢?”

UPDATE: If the framework can't know the type of a null pointer, can't it know what type it's supposed to be? 更新:如果框架不知道空指针的类型,就不能知道它应该是什么类型? Well, it might. 好吧,可能吧。 Then again, it might not. 再说一次,可能不会。 Consider: 考虑:

 MyClass myobj = null;
 int hash = myobj.GetHashCode();

Unless you overrode it in MyClass, GetHashCode is defined in System.Object. 除非您在MyClass中覆盖它,否则GetHashCode是在System.Object中定义的。 Should you get a complaint that myobj needs to be a System.Object? 您是否应该抱怨myobj必须是System.Object? Now, when we check ourselves, we're completely free to specify the required type. 现在,当我们检查自己时,我们完全可以自由指定所需的类型。

  SomeFunc(MyClass myparam)
  {
       if (myparam == null)
           throw new ArgumentNullException("myparam must be a MyClass object");
  }

But now we are talking about application code, not CLR code. 但是现在我们正在谈论应用程序代码,而不是CLR代码。 Which makes you "real" question "Why don't people write more informative exception messages?", which is, as we say here at SO " subjective and argumentative " 这使您成为“真正的”问题,“人们为什么不写更多翔实的异常消息?”,正如我们在此处所说的那样,这是“ 主观和争论

So, you basically want the system level exception to know the type information which is only known at the applications level, which we'd need so way to communicate. 因此,您基本上希望系统级异常知道仅在应用程序级才知道的类型信息,因此我们需要通过这种方式进行通信。 Something like: 就像是:

  SomeFunc(MyClass myparam)
  {
       if (myparam == null)
           throw new ArgumentNullException("myparam", typeof(MyClass));
  }

But that's not really buying us much, and if you really want it, you could write it yourself: 但这并不能真正为我们买很多东西,如果您真的想要,可以自己编写:

  public class MyArgumentNullException : ArgumentNullException
  {
      public MyArgumentNullException(string name, Type type) 
          :base(name + "must be a " + type.Name + " object");
  }

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM