获取未设置为对象实例的对象引用的空引用对象的类型
自从我开始编程以来,这个问题一直困扰着我,不是“我的代码在哪里为空”,而是有什么方法可以从异常中获取为空的对象的类型吗?
如果做不到这一点,任何人都可以提供博客文章或 msdn 文章来解释 .NET Framework 不(或不能)提供这些详细信息的原因吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嗯...因为它是空的。
在 C# 中,引用类型是指向某物的指针。空指针不指向任何东西。你在问,“如果它指向某物,它会指向什么类型的东西”。这有点像拿一张白纸,然后问:“如果上面写着什么,这会说什么?”
更新:如果框架无法知道空指针的类型,它就不能知道它应该是什么类型吗?嗯,可能是这样。话又说回来,可能不会。考虑一下:
除非您在 MyClass 中覆盖它,否则 GetHashCode 是在 System.Object 中定义的。您是否会收到关于 myobj 需要是 System.Object 的抱怨?现在,当我们检查自己时,我们可以完全自由地指定所需的类型。
但现在我们讨论的是应用程序代码,而不是 CLR 代码。这让你产生“真正的”问题“为什么人们不写更多信息丰富的异常消息?”,正如我们在 SO 所说的“主观和争论性”
所以,你基本上想要系统级别例外以了解仅在应用程序级别已知的类型信息,我们需要这种方式进行通信。类似这样的:
但这并没有给我们带来太多好处,如果你真的想要它,你可以自己写:
Um... Because it's null.
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:
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.
But now we are talking about application code, not CLR code. 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:
But that's not really buying us much, and if you really want it, you could write it yourself: