在C#中这两种方式初始化对象之间的差异 [英] difference between initializing an object with these two ways in c#

查看:142
本文介绍了在C#中这两种方式初始化对象之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常我即时初始化对象将其添加到列表时
用这种方法--->

  list.add(
新富( ){//< ---富()
字段1 =值1,
场2 =值
}
);



但一旦我只是想--->

  list.add(
新富{//< ---富
字段1 =值1,
场2 =值
}
);



&安培;它的工作!



在第二种方法我只是创建对象不使用()在它的尾巴。
因此,没有人对这些不同的方法来初始化对象之间的差异的想法?


解决方案

因此,没有人对这些不同的方法来初始化对象之间的差异的想法?




有什么区别可言。在这两种情况下,你使用的是对象初始化的,如果你没有指定任何构造函数的参数,这是的究竟的相当于提供的构造函数的参数列表为空。从C#规范第7.6.10.1:




对象创建表达式可以省略构造函数参数列表和圆括号提供它包括一个对象初始化或集合初始化。省略构造函数参数列表和圆括号相当于指定一个空的参数列表。




请注意,当你的只是调用构造函数不使用对象初始化(括号),你的有无的指定构造函数的参数。所以:

 富富=新的Foo(); //有效
富富=新富; //无效
富富=新的Foo(){}; //有效
富富=新的Foo {}; //有效



有效线都完全等同,包括任何使用默认参数 - 这样也许只有这样的构造:

  //你可以调用此不指定参数
公共美孚(INT X = 0)
{
}

有关详细信息,请参阅C#5规范第7.6.10。


generally i instant initialize an object when adding it to a list with this way --->

list.add(
   new foo() {                       //     <--- foo()
      field1 = value1,
      field2 = value2 
   }
);

but once i just tried --->

list.add(
   new foo {                     //     <--- foo
      field1 = value1,
      field2 = value2 
   }
);

& it worked !!!

in the 2nd way i am just creating an object without using () at tail of it. so does anyone have any idea about the difference between these various ways to initializing an object ?

解决方案

so does anyone have any idea about the difference between these various ways to initializing an object ?

There's no difference at all. In both cases you're using an object initializer, and if you don't specify any constructor arguments, that's exactly equivalent to providing an empty list of constructor arguments. From section 7.6.10.1 of the C# spec:

An object creation expression can omit the constructor argument list and enclosing parentheses provided it includes an object initializer or collection initializer. Omitting the constructor argument list and enclosing parentheses is equivalent to specifying an empty argument list.

Note that when you just invoke a constructor without using an object initializer (the braces) you have to specify the constructor arguments. So:

Foo foo = new Foo();    // Valid
Foo foo = new Foo;      // Invalid
Foo foo = new Foo() {}; // Valid
Foo foo = new Foo {};   // Valid

The "valid" lines are all exactly equivalent, including any use of default parameters - so Foo might only have a constructor like this:

// You can invoke this without specifying arguments
public Foo(int x = 0)
{
}

See section 7.6.10 of the C# 5 spec for more details.

这篇关于在C#中这两种方式初始化对象之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆