C# 中的“new object()”和“new {}”有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17586525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:55:44  来源:igfitidea点击:

What is the Difference Between `new object()` and `new {}` in C#?

c#.net

提问by Idrees Khan

First of all i searched on this and i found the following links on Stack Overflow:

首先,我对此进行了搜索,并在 Stack Overflow 上找到了以下链接:

But i'm not satisfiedwith this answer, it's not explained well (i didn't get it well). Basically, i want to know the difference between new object()and new {}. How, they are treated at compile time and runtime?

但是我这个答案并不满意,它没有得到很好的解释(我没有得到很好的解释)。基本上,我想知道的区别 new object()new {}它们在编译时和运行时如何处理?

Secondaly, i have the following code which i have used for WebMethodsin my asp.net simple application

其次,我WebMethods在我的 asp.net 简单应用程序中使用了以下代码

[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static object SaveMenus(MenuManager proParams)
{
    object data = new { }; // here im creating an instance of an 'object' and i have typed it `new {}` but not `new object(){}`.
    try
    {
        MenuManager menu = new MenuManager();    
        menu.Name = proParams.Name;
        menu.Icon = proParams.Icon;
        bool status = menu.MenuSave(menu);
        if (status)
        {
            // however, here i'm returning an anonymous type
            data = new
            {
                status = true,
                message = "Successfully Done!"
            };
        }
    }
    catch (Exception ex)
    {
        data = new { status = false, message = ex.Message.ToString() };
    }
    return data;
}

So, (as you can see in comments in code), How new object(){}and new {}differences?

那么,(正如您在代码的注释中所见),如何new object(){}new {}差异?

Is this even the right way that i have write the code?Can you suggest a best way for this code?

这甚至是我编写代码的正确方法吗?你能为这段代码建议一个最好的方法吗?

I know, i can't explain it well and i'm asking alot, but that's the best i have right now.

我知道,我不能很好地解释它,我问了很多,但这是我现在最好的。

采纳答案by Dmitry Bychenko

new {...}always creates an anonymous object, for instance:

new {...}总是创建一个匿名对象,例如:

  Object sample = new {};
  String sampleName = sample.GetType().Name; // <- something like "<>f__AnonymousType0" 
                                             //                    not "Object"

while new Object()creates an instance of Objectclass

whilenew Object()创建一个Object类的实例

  Object sample = new Object() {};
  String sampleName = sample.GetType().Name; // <- "Object"

since all objects (including anonymous ones) are derived from Objectyou can always type

因为所有对象(包括匿名对象)都是从Object你派生的,你总是可以输入

  Object sample = new {};

回答by CodesInChaos

new{ }creates an instance of an anonymous type with no members. This is different from creating an instance of object. But like almost all types, anonymous types can be assigned to object.

new{ }创建一个没有成员的匿名类型的实例。这与创建 的实例不同object。但是和几乎所有类型一样,匿名类型可以分配给对象。

 object data = new { };
 Console.WriteLine(data.GetType().Name)

Clearly shows an auto-generated name, not Object.

清楚地显示自动生成的名称,而不是Object.

回答by NPSF3000

To see the difference between new Object()and new {}and new Object(){}... why don't we just find out?

看看new Object()and 和new {}and之间的区别new Object(){}……我们为什么不找出来呢?

Console.WriteLine(new Object().GetType().ToString());
Console.WriteLine(new Object() { }.GetType().ToString());
Console.WriteLine(new { }.GetType().ToString());

The first two are just different ways of creating an Object and prints System.Object. The third is actually an anonymous type and prints <>f__AnonymousType0.

前两种只是创建 Object 和 prints 的不同方式System.Object。第三个实际上是一个匿名类型并打印<>f__AnonymousType0.

I think you might be getting confused by the different uses of '{}'. Off the top of my head it can be used for:

我认为您可能会对“{}”的不同用法感到困惑。在我的头顶,它可以用于:

  1. Statement blocks.
  2. Object/Collection/Array initialisers.
  3. Anonymous Types
  1. 语句块。
  2. 对象/集合/数组初始值设定项。
  3. 匿名类型

So, in short object data = new { };does not create a new object. It creates a new AnonymousType which, like all classes, structures, enumerations, and delegatesinherits Object and therefor can be assigned to it.

所以,总之object data = new { };不会创建新对象。它创建了一个新的 AnonymousType,与所有类、结构、枚举和委托一样,它都继承了 Object,因此可以将其分配给它。



As mentioned in comments, when returning anonymous types you still have declare and downcast them to Object. However, they are still different things and have some implementation differences for example:

正如评论中提到的,在返回匿名类型时,您仍然需要声明并将它们向下转换为 Object。但是,它们仍然是不同的东西,并且有一些实现差异,例如:

static void Main(string[] args)
{
    Console.WriteLine(ReturnO(true).ToString());  //"{ }"
    Console.WriteLine(ReturnO(false).ToString());  // "System.Object"

    Console.WriteLine(ReturnO(true).Equals(ReturnO(true)));  //True
    Console.WriteLine(ReturnO(false).Equals(ReturnO(false)));  //False
    Console.WriteLine(ReturnO(false).Equals(ReturnO(true)));  //False

    Console.WriteLine(ReturnO(true).GetHashCode());  //0
    Console.WriteLine(ReturnO(false).GetHashCode());  //37121646

    Console.ReadLine();
}

static object ReturnO(bool anonymous)
{
    if (anonymous) return new { };
    return new object();
}