Is there any difference between `new object()` and `new {}` in c#?

僤鯓⒐⒋嵵緔 提交于 2020-01-03 08:54:13

问题


in c#,

var x = new {};

declares an anonymous type with no properties. Is this any different from

var x = new object();

?


回答1:


Yes, the types used are different. You can tell this at compile-time:

var x = new {};
// Won't compile - no implicit conversion from object to the anonymous type
x = new object(); 

If you're asking whether new{} is ever useful - well, that's a different matter... I can't immediately think of any sensible uses for it.




回答2:


Well, for starters, object is an actual, non-anonymous type...if you do x.GetType() on the 2nd example, you'll get back System.Object.




回答3:


Along with the return from GetType as mentioned, x would not be of type object, so you would not be able to assign an object type to that variable.

        var x = new { };
        var y = new object();

        //x = y; //not allowed
        y = x; //allowed



回答4:


Jon Skeet's answer was mostly what I wanted, but for the sake of completeness here are some more differences, gained from reflector:

new {} overrides three methods of object :

  1. Equals - as mentioned in other answers, new object and new {} have different types, so they are not equal.
  2. GetHashCode returns 0 for new {} (but why would you put it in a hash table anyway?)
  3. ToString prints "{}" for new {}

Unfortunately I can't think of a practical application for all this. I was just curious.



来源:https://stackoverflow.com/questions/1027997/is-there-any-difference-between-new-object-and-new-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!