Answer the question
In order to leave comments, you need to log in
How to correctly inherit from a generic class without a compiler error?
I pulled out code from my application (without unnecessary specifics), which leads to a compiler error.
public class DataObject
{
public string Id { get; set; }
public int ObjType { get; set; }
}
public class ReferredObject : DataObject
{
public string Name { get; set; }
public string Remark { get; set; }
}
public class Model<TDataObject> where TDataObject : DataObject, new()
{
}
// строка ниже, ошибка компилятора: CS0310
public class RefferedObjectModel<TDataObject> : Model<TDataObject>
where TDataObject : ReferredObject
{
}
'TDataObject' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TDataObject' in the generic type or method 'Program.Model'
Answer the question
In order to leave comments, you need to log in
Thanks Anton Baryshev for the solution, you need to add the new () option
public class RefferedObjectModel<TDataObject> : Model<TDataObject>
where TDataObject : ReferredObject, new()
what is the requirement of the compiler?
Hello.
Do you really need the type in the generic class declaration to have a public parameterless constructor? If you remove , then everything is without errors:, new()
public class Model<TDataObject> where TDataObject : DataObject
{
public Model()
{
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question