Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - How to pass C# class and its subclasses as generics?
How to pass C# class and its subclasses as generics?
In C#, common classes and abstract classes do not support covariation, so if you want to use covariation, you have to use interfaces.

Covariance, such as interface ia and its subclass AA.

IA & ltBaseQueryInfo & gta = new aa & ltmultiborowtag & gt (...)//Ok, correct covariation.

AA & ltBaseQueryInfo & gta = new aa & ltmultiborowtag & gt (...)//Error, covariation is not allowed!

Definition of covariant interface:

Interface IA & ltout T & gt// This out is very important, indicating that this interface supports covariation.

{

void F(); //ok

t G(); //Well, covariation allows generic parameters as return values.

void H(T T); //Error, covariation does not allow generic parameters as function parameters.

}

Therefore, the solution 1: When declaring the DataTagEnumQueryDict variable, use the parent interface of DataProcessEntity that declares out instead. For example, suppose there is an interface idataprocess.

It is declared as:

Private static dictionary & ltDataTagEnum, idataprocess & ltbasequeryinfo & gt & gtdatatagenumquery dictionary = new. ...

Solution 2:

What if the class DataProcessEntity doesn't declare the parent interface of out at all? No way, we can only have new data processing entities.

Solution 3: If you don't want to be new? Data processing entity & ltBaseQueryInfo & gt{...}, what should I do? There is a more tortuous way:

Define your own interface!

Interface idataprocessentitydelegator < out T & gt

{

void AAA(); //Copy the method signature of DataProcessEntity to be used as it is, but never copy the method signature using t as the method parameter.

t BBB();

....

}

redefinition

Principal of Class Data Processing Entity & ltT>

{

Private read-only data processing entity;

Principal of public data processing entity & ltout T & gt(A a, B b, C c ...)

{

Entity = New? Data processing entities (a, b, c ...);

}

public void AAA()= & gt; Entity. AAA();

Public? t BBB()= & gt; ? Entity. BBB(); //Note: This is shorthand grammar after C#6.0, otherwise write a complete function body yourself.

}

Then, you can write code happily:

Private static dictionary & ltDataTagEnum,? IDataProcessEntityDelegator & lt; BaseQueryInfo & gt& gtDataTagEnumQueryDict = new ...

......

DataTagEnumQueryDict。 Add (..., data processing entity principal & ltbasequeryinfo & gt {...});

DataTagEnumQueryDict。 Add (..., data processing entity principal & ltmultiborowtag & gt {...}? );

DataTagEnumQueryDict。 Add (..., data processing entity principal < blacklist label > {...}? );

Which method to use depends on your consciousness.