如何编写一个可以包含其他相关类的类?

时间:2015-06-29 19:30:02

标签: c# design-patterns

是否可以编写一个类似于其他两个类的超类的类。

例如,我有A类和B类.A和B共享相似的属性,但由于我没有编写A或B代码,因此它们不扩展接口或类。我是否可以创建这个超类,以便在我概括我的代码时它可以处理A类或B类。

如果可以创建这个超类,这是我想在课堂上做的一些事情

class A
{
    string Name { get; set;}
    //does stuff
    //I can't change this class
}

class B
{
    string Name { get; set;}
    //does similar stuff
    //I can't change this class either
}

class MyClass
{
    //I would like to create a list that can include both class B and class A
    List<(pseudo superclass of A and B)> list;

    //Both class A and class B have a name, I would like to get the name given a type of A or B
    public (pseudo superclass of A and B) GetName((pseudo superclass of A and B) AorB)
    {
        //Write that name to the console
        Console.WriteLine(AorB.Name);
    }

}

这种包装是否可行,或者我是否需要在MyClass中做更多工作(例如重载方法)以完成我需要的工作。

1 个答案:

答案 0 :(得分:2)

我建议,

1创建一个界面:

interface IWrapper
{
    string Name { get; set; }
    ...
}

2创建包装类:

class WrapperA : IWrapper
{
    private A _a;

    public WrapperA(A a) { _a = a; }

    public Name
    {
        get { return _a.Name; }
        set { _a.Name = value; }
    }
    // other properties here
}

同样适用BWrapper周围的B

然后你可以创建你的课程:

class MyClass
{
    List<IWrapper> list;

    public string GetName(IWrapper aOrB)
    {
        Console.WriteLine(aOrB.Name);
    }
}