Base Class B
|
|
----
| |
| |
D1 D2
public static object GetDerivedClass(Type t1, MyProce开发者_JAVA技巧ss p1)
{
DerivedClass D1 = null;
DerivedClass D2 = null;
if (t1 is typeof(Derived)
{
Process(D1,p1);
return D1;
}
else if(t1 is typeof(Derived)
{
Process(D2,p1);
return D2;
}
}
My Question is what will be the generic way to return the type of object which is passed as t1 Type,
because in real implementation I have deep hierarchy of my design pattern with lots of D1,D2,etc...
You could re-write your Process
method as a generic method, i.e.
T Process<T>(MyProcess p1) where T : new
{
// do work
// apparently your Process method must be creating a new instance
// this is why I put the new constraint on the type parameter
T t = new T();
// set properties of t, etc.
return t;
}
Your GetDerivedClass
method is now redundant. Simply call the Process
method as follows:-
var obj = Process<MyDerivedType>(p1);
精彩评论