获取空引用对象的类型,对象引用不设置到对象的实例对象、实例、类型

2023-09-04 00:48:34 作者:久病成欢孤独成瘾

自从我开始编程这个问题一直烦我,而不是哪里是我的code空,但具体有没有什么办法让那就是空的例外对象的类型?

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?

如果做不到这一点,任何人都可以提供博客文章或MSDN文章,解释了为什么.NET Framework并不是理由(或不能)提供这些信息?

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?

推荐答案

嗯......因为它是空。

Um... Because it's null.

在C#中,引用类型是一个指针的东西。空指针不指向任何东西。你问:什么样的事情会这一点上,如果它指向的东西。这有点像得到的一张白纸,并问道:你会这样说,如果它有东西写在上面?

In C#, a reference type is a pointer to something. 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();

除非你在MyClass的推翻它,GetHash code是System.Object的定义。如果你得到MyObj中需要一个System.Object的投诉?现在,当我们检查自己,我们是完全免费的,指定所需的类型。

Unless you overrode it in MyClass, GetHashCode is defined in System.Object. Should you get a complaint that myobj needs to be a 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");
  }

但现在,我们正在谈论的应用code,不是CLR code。它让你真实的问题:为什么不写的人更多的信息异常消息?,这是因为我们在这里说,在如此的的主观和争论的

所以,你基本上要在制度层面例外知道哪只知道在应用层面,我们就需要这样的沟通方式类型的信息。是这样的:

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");
  }