What is the syntax for a default constructor for a generic class?

后端 未结 3 1489
北荒
北荒 2020-12-13 01:36

Is it forbidden in C# to implement a default constructor for a generic class?

If not, why the code below does not compile? (When I remove it c

相关标签:
3条回答
  • 2020-12-13 01:47

    You don't provide the type parameter in the constructor. This is how you should do it.

    public class Cell<T> 
    {
        public Cell()
        {
        }
    }
    
    0 讨论(0)
  • 2020-12-13 01:48

    And if you need to inject an instance of the type:

    public class Cell<T>
    {
        public T Thing { get; }
    
        public Cell(T thing)
        {
            Thing = thing;
        }
    }
    
    0 讨论(0)
  • 2020-12-13 01:54

    And if you need the Type as a property:

    public class Cell<T>
    {
        public Cell()
        {
            TheType = typeof(T);
        }
    
        public Type TheType { get;}
    }
    
    0 讨论(0)
提交回复
热议问题