문제

I am trying to create an object using c# object initializer. But that class already has a constructor with one argument as per the need and I dont have a need for a default construcor so I didn't provide one. Compiler too won't provide a default constructor when there is a user-provided constructor in the class.

Now the problem arises when I try to create an instance of this class using an object initializer:

public class Foo
{
    public int Data { get; set; }
    public Foo(int Data)
    {
        this.Data = Data;
    }
}

I instantiate the class like this:

 Foo f=new Foo { Data=10};

And now I'm getting a compile-time error:

"Foo does not contain a constructor that takes 0 argument"

I know the error, it's because of the lack of a default constructor. When I don't have a need for the default constructor why should I provide one just for using object initializer? So I am just wondering, is there is any other way (style, syntactically) I can use this object initializer without explicitly providing a default constructor?

I checked this MSDN link, it says if you have a PRIVATE default constructor in your class you can't use object initializer, but I dont have a private default constructor here.

도움이 되었습니까?

해결책

If you already have a constructor accepting the argument you require to properly initialize the object, then why not use the proper constructor syntax?

Foo f = new Foo { Data = 10 };  // What you want (object initializer syntax)
Foo f = new Foo ( Data : 10 );  // What you can get (constructor syntax)

다른 팁

Then don't use the object initialiser. Just pass the value in via the constructor:

Foo f=new Foo(10);

If you want to use the object initialiser, you can:

Foo f=new Foo(10){ Data=10};

But you are setting the same value twice so there's no point

The object initializer syntax is shorthand for something like this:

var x = new MyClass();
x.Property1 = "value1";
x.Property2 = "value2";
x.Property3 = "value3";
...

You can verify this by creating a default constructor with dummy content and a breakpoint, and then instantiating the class with an object initializer; the breakpoint will be hit, even though you're not explicitly calling the default constructor.

So when you do var x = new MyClass { Property1 = "value1", Property2 = "value2, Property3 = "value3" };. you are calling the default constructor. If it's missing, you get the compile-time error you noticed.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top