Home > Net > Subclasses parent transformation problem
Subclasses parent transformation problem
Time:11-18
As follows: Public class ParentClass {
} Public class ChildAClass: ParentClass {
} Public class ChildBClass: ParentClass {
}
Public T GetChild (ParentClass PC, string classType) { //for expert advice on how to write, in this will return a generic }
Parameters for the type of parent and child classes, output parameters for the subclasses of generics; Parameter in the PC to ensure can be converted into subclasses
CodePudding user response:
This writing don't you call a generic, generic is characterized by: specified type at runtime, you only have one T, the return value is that there is no specified type "" ah, you write the overall framework of has a problem, not just fill in the blanks of how to write the code, to change the framework code,
CodePudding user response:
I guess you want to get a subclass by classType Type (Type)? Because if just type conversion, you don't need to write like this, directly (PC as T) Don't need a paradigm, do not need to pass the superclass object
Public static Type GetChild (string classType) => The Assembly GetExecutingAssembly () The GetTypes () The Where (t=& gt; Typeof (ParentClass). IsAssignableFrom (t) & amp; & T.N ame==classType) FirstOrDefault ();
CodePudding user response:
Since want to convert, that will define the scope of T, generic inheritance,
public class ParentClass {
} Public class ChildAClass: ParentClass {
} Public class ChildBClass: ParentClass {
}
Public class ClassTest T: where ParentClass { Public T GetChild (ParentClass PC, string classType) { Return PC (T); } }