开发者

C# Struct Generic Constructor [duplicate]

This question already has answers here: How can I set the value of auto property backing fields in a struct constructor? (2 answers) Closed 9 years ago.

Using this code:

struct Foo<T1>
{
    public T1 Item1 { get; private set; }

    public Foo(T1 item1)
    {
        Item1 = item1;
    }
}

I encounter this error:

Backing field for automatically implemented property 'Foo.Item1' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.

My question is, why is the p开发者_开发百科roperty Item1 not fully assigned after the constructor is called?

Edit: Changed set to private set because this question has nothing to do with mutability.


Add this() in here:

public Foo(T1 item1) : this()
{
    Item1 = item1;
}

It's because you're assigning to a property, and the compiler can't deduce that the property only assigns a value to a variable; it could do other things before the instance is initialized, and that's not allowed because the structure might have garbage data. So you have to initialize it with the default constructor first, then do what you want.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜