开发者

New constructors in .NET 3.5

开发者 https://www.devze.com 2022-12-10 00:59 出处:网络
This is a simple question really. I\'ve been using the new type of constructors in .NET 3.5 (C#), but I would like to know what they\'re are called, if they\'ve got a name at all :)

This is a simple question really. I've been using the new type of constructors in .NET 3.5 (C#), but I would like to know what they're are called, if they've got a name at all :)

The constructor I'm talking about is thi开发者_如何学Pythons:

Customer c = new Customer()
{
    Name = "Bo"
};


You're using the regular parameterless constructor but also the new feature which is called an Object Initializer.


As others have already noted, they are called Object Initializers.

However, they are not constructors, and you shouldn't go around referring to them as such.

Consider the following code:

public class TestHarness
{
    static void Main(string[] args)
    {
        Class1 class1 = new Class1();
        class1.Foo = "foo";

        Class2 class2 =
            new Class2
            {
                Foo = "foo"
            };
    }
}

public class Class1
{
    public string Foo { get; set; }
    public string Bar { get; set; }
}

public class Class2
{
    public string Foo { get; set; }
    public string Bar { get; set; }
}

Look at the IL generated for the Main method:

.method private hidebysig static void Main(string[] args) cil managed
{
    .maxstack 2
    .locals init (
        [0] class ClassLibrary1.Class1 class2,
        [1] class ClassLibrary1.Class2 class3,
        [2] class ClassLibrary1.Class2 class4)
    L_0000: nop 
    L_0001: newobj instance void ClassLibrary1.Class1::.ctor()
    L_0006: stloc.0 
    L_0007: ldloc.0 
    L_0008: ldstr "foo"
    L_000d: callvirt instance void ClassLibrary1.Class1::set_Foo(string)
    L_0012: nop 
    L_0013: newobj instance void ClassLibrary1.Class2::.ctor()
    L_0018: stloc.2 
    L_0019: ldloc.2 
    L_001a: ldstr "foo"
    L_001f: callvirt instance void ClassLibrary1.Class2::set_Foo(string)
    L_0024: nop 
    L_0025: ldloc.2 
    L_0026: stloc.1 
    L_0027: ret 
}

You can see that the compiler has generated code which sets the Foo property for both class1 and class2. It did not generate a constructor which takes and sets Foo. A minor point, but it's best to understand the difference.


They are called Object Initializers. More info about them can be found here: http://weblogs.asp.net/dwahlin/archive/2007/09/09/c-3-0-features-object-initializers.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消