【问题标题】:inheritence how to return the subclass object?继承如何返回子类对象?
【发布时间】:2010-12-20 14:13:34
【问题描述】:
    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;
     }
}

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

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

【问题讨论】:

  • 困惑...图中的 D1 / D2 是一个 type 吗?还是(根据 C# 示例)一个变量? Process 的签名有哪些?
  • 我认为该图代表了一个类层次结构......
  • 我的意思是它与代码示例根本不符...
  • 当然......样本很模糊;o)那只是我的两分钱......
  • 问题很简单,我假设有 3 个基类派生类,并根据函数中传递的参数类型,我想返回该类型的实例,但为此我必须采用 3 个本地派生类变量,到目前为止,如果我有 10 个这样的类型,我必须在该函数中删除 10 个 DerivedClass 变量。

标签: c# .net design-patterns inheritance


【解决方案1】:

您可以将 Process 方法重写为通用方法,即

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;
}

您的GetDerivedClass 方法现在是多余的。只需调用Process方法如下:-

var obj = Process<MyDerivedType>(p1);

【讨论】:

    猜你喜欢
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多