开发者

inheritence how to return the subclass object?

开发者 https://www.devze.com 2022-12-12 07:59 出处:网络
Base Class B ---- D1D2 public static object GetDerivedClass(Type t1, MyProce开发者_JAVA技巧ss p1)
    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);
0

精彩评论

暂无评论...
验证码 换一张
取 消