Generics used in struct vs class

前端 未结 4 2083
半阙折子戏
半阙折子戏 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:28

    That's a requirement of structs in general -- it has nothing to do with generics. Your constructor must assign a value to all fields.

    Note the same error happens here:

    struct Foo
    {
        public int A;
        public int B;
    
        public Foo()
        {
            A = 1;
        }
    }
    
    0 讨论(0)
  • 2021-02-13 12:40

    The other answers explain the behaviour correctly, but neglect to mention the second part of your question, so here it is for completion.

    When you don't explicitly define a constructor, the compiler will produce a default constructor which assigns default values (e.g. null for objects, 0 for numbers etc.) to every field.

    0 讨论(0)
  • 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?

    0 讨论(0)
  • 2021-02-13 12:43

    Because it is a rule in C# that all fields must be assigned for structs (inline or in constructor). This is because of a struct nature. It has nothing about generic it or not generic.

    0 讨论(0)
提交回复
热议问题