如何实例化派生类而不是其基类

时间:2018-09-27 06:06:03

标签: c# class override derived-class

这是我的问题: 我有一个在B类中多次使用(实例化)的A类。

我需要更改A类(主要是构造函数)的行为,然后由C类派生。 C级:A级

我希望类B在其方法中使用类C而不是类A,以避免覆盖使用它的所有方法。 有可能吗?

非常感谢


我不清楚,因此让我尝试用代码更好地解释。

Public Class A
{
`// Simple constructor
    public A(params[])
    {
        // things here
    }
}

Public Class C : A
{
    // Constructor doing different thing then base
    public C(params[]): base(params[])
    {
        // do different things here
    }
}

Public class B
{
    public B(params[])
    {    }

    public method_A(params[])
    {
        A _temp = new A(params[]);
        // do things here with A
    }
}

我在程序中使用B,但我希望B的一种形式使用A,B的另一种实例使用C而不是A。

类似的东西:

Main()
{
   B _instance1 = new B();

   B _instance2 = new B(); 

   // use instance 1
   _instance1.method_A(...);
   // use instance 2 
   _instance2.method_A(...); // do something here for using C instead of A in the method
}

1 个答案:

答案 0 :(得分:1)

只需实例化B类中的C类并像使用A类一样使用它,它将具有与A相同的功能,并在C类中添加了逻辑。

在构造函数中,可能值得做以下事情:

public class C : A
{
    public C() : base()
    {
     // do stuff
    }
}

以便它也将调用A的构造函数。