繁体   English   中英

是否可以在不修改基类的情况下从派生类中更改基类方法中使用的类型?

[英]Is it possible to change the type used in a method of a base class from within a derived class without modifying the base class?

假设我们有四个类A,B,T和U,它们看起来像这样:

using System;
using bla;


public class T
{
    public void method()
    {
        Console.WriteLine("I am using T.");
    }
}

public class U : T
{
    public new void method()
    {
        Console.WriteLine("I am using U.");
        // other stuff...
    }
}

public class A
{
    public T t;
    public void method()
    {
        t = new T();
        t.method();
        // some important manipulations of t...
    }
}

namespace bla{
    using T = U;
    public class B : A
    {
        public new void method()
        {
            // now use type U instead of T in the base method.
            base.method();
            // other stuff...
        }    
    }
}

public class Test
{
    public static void Main()
    {
        B b = new B();
        b.method();
    }
}

我想实现的是,当从类B中调用基本方法base.method()时,实际上使用的是类型U,而不是类型T。这样, Main()方法的输出将是:

I am using U.

是否可以在C#中实现而无需修改类A和/或T 诸如using指令之类的东西会很好。 上面的代码-显然-不能按我的要求工作。 我也考虑过使用反射,但是我不确定在这种情况下是否可以使用反射而不必实例化一个新的(匿名)对象或引用一个现有的对象(在我的情况下这都不是一件好事)。

否则,我将不得不通过用U替换每个T或在开头插入using指令(或接受参数,或使用模板)来修改A类(将B类几乎逐行复制),以替换A类管他呢)。 无论哪种方式,我都觉得这不是很整洁,我想知道它是否可以更好地实现。

我是否缺少明显的东西? 在此先感谢您的帮助!

短的答案:无,鉴于目前的结构,这是无法接受base.method()这是一个从称为B使用methodU代替T而不修改既不A也不T 但是,为什么不只是:

public class B : A
{
    public new void method()
    {
        U u = new U();
        u.method();
    }    
}

我还没有尝试过,但是您可以确定将对象强制转换为想要的基类。

像这样:

((U)this).method();

编辑:使用类型T而不是类型U的原因是,在类A中存在类型T的实例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM