Class Mapping Error: 'T' must be a non-abstract type with a public parameterless constructor

前端 未结 3 971
青春惊慌失措
青春惊慌失措 2020-12-01 03:06

While mapping class i am getting error \'T\' must be a non-abstract type with a public parameterless constructor in order to use it as parameter \'T\' in the generic type or

相关标签:
3条回答
  • 2020-12-01 03:48

    I had the same issue. I should have read the message before Googling it. I needed to add a parameterless constructor ... :-)

    public MyClass() {
      //stuff
    }
    
    0 讨论(0)
  • 2020-12-01 04:03

    The constraints must apply to every type in the chain; hence you need:

    public abstract class SqlReaderBase<T> : ConnectionProvider where T : new()
    

    Without this, you can't satisfy the constraint for T in:

    protected abstract MapperBase<T> GetMapper();
    

    or

    MapperBase<T> mapper = GetMapper();
    

    since MapperBase<> is only usable when T has : new()

    0 讨论(0)
  • 2020-12-01 04:05

    The problem is that you're trying to use the T from SqlReaderBase as the type argument for MapperBase - but you don't have any constraints on that T.

    Try changing your SqlReaderBase declaration to this:

    public abstract class SqlReaderBase<T> : ConnectionProvider
        where T : new()
    

    Here's a shorter example which demonstrates the same issue:

    class Foo<T>
    {
        Bar<T> bar;
    }
    
    class Bar<T> where T : new()
    {
    }
    

    The fix is to change Foo<T>'s declaration to:

    class Foo<T> where T : new()
    

    Then the compiler will know that the T from Foo is a valid type argument for Bar.

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