Generics used in struct vs class

前端 未结 4 2082
半阙折子戏
半阙折子戏 2021-02-13 12:10

Assume that we have the following struct definition that uses generics:

public struct Foo
{
    public T First; 
    public T Second;

             


        
4条回答
  •  野的像风
    2021-02-13 12:43

    That is because a compiler rule enforces that all fields in a struct must be assigned before control leaves any constructor.

    You can get your code working by doing this:

    public Foo(T first)
    {
        this.First = first;
        this.Second = default(T);
    }
    

    Also see Why Must I Initialize All Fields in my C# struct with a Non-Default Constructor?

提交回复
热议问题