Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 继承如何返回子类对象?_C#_.net_Design Patterns_Inheritance - Fatal编程技术网

C# 继承如何返回子类对象?

C# 继承如何返回子类对象?,c#,.net,design-patterns,inheritance,C#,.net,Design Patterns,Inheritance,我的问题是,返回作为t1类型传递的对象类型的通用方法是什么 因为在实际实现中,我的设计模式有很深的层次结构,有很多D1、D2等。您可以将过程方法作为通用方法重新编写,即 Base Class B | | ---- | | | | D1 D2 public static object GetDerivedClass(Type t1, MyProcess p1) { DerivedClass D1 = null;

我的问题是,返回作为t1类型传递的对象类型的通用方法是什么


因为在实际实现中,我的设计模式有很深的层次结构,有很多D1、D2等。

您可以将
过程
方法作为通用方法重新编写,即

    Base Class B
    |
    |
    ----
    |   |
    |   |
    D1  D2

public static object GetDerivedClass(Type t1, MyProcess 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;
     }
}

困惑的图中D1/D2是否为a型?或者(根据C#示例)一个变量?流程的特征是什么?我认为该图代表了一个类层次结构…我的观点是它与代码示例完全不符…当然。。。样本相当模糊;o) 这只是我的2美分…问题很简单,我假设3个派生类的基类,根据函数中传递的参数类型,我想返回该类型的实例,但为此,我必须获取3个局部派生类变量,到目前为止,如果我有10个这样的类型,我必须在该函数中删除10个派生类变量。
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;
}
var obj = Process<MyDerivedType>(p1);