2

以下代码:

class Program
{
    static P1 p = new P1();
    static void Main(string[] args)
    {
        var t = new P2();
        p = t;
        p.DoWork();
        t.DoWork();
        Console.ReadLine();
    }
}

public class P1
{
    public void DoWork()
    {
        Console.WriteLine("Test1");
    }
}
public class P2: P1
{
    new public void DoWork()
    {
        Console.WriteLine("Test2");
    }
}

将打印出:

Test1
Test2

无论如何强制调用 p.DoWork() 使用 P2 类中的实现。实际上,P1 类在第三方编译的程序集中,因此我无法修改 P1 类的任何代码。通常我只会将 virtual 关键字添加到 P1 但这是不可能的。

4

3 回答 3

3

不。

的作者P1没有选择将他们的DoWork方法虚拟化。所以你不能改变那个方法的作用。

不要引入与fromnew具有相同名称和签名的方法。它会导致混乱。它不会以任何方式改变原件。相反,为您自己的方法选择一个新名称。DoWorkP1DoWork

如果P1不是在所有情况下都需要的功能,也许你根本不应该继承P1。相反,您的类可以拥有一个私有类型的字段,P1然后您的某些方法可以使用P1.

于 2013-07-28T09:47:46.617 回答
1

您可以像这样将 P1 实例转换为 P2:

((p2)p).DoWork();

或者,您可以构建一个内部使用 P1 实例的包装类。内部类所需的所有内容都会被重定向,您可以自由地将适合您的内容添加到包装类中。

public class P1
{
    public string SomeProperty { get; set; }

    public int SomeMethod()
    {
        return 0;
    }

    public void DoWork()
    {
        // Do something
    }
}

public class Wrapper
{
    private P1 Instance { get; set; }

    public string ExposedProperty
    {
        get
        {
            return this.Instance.SomeProperty;
        }
    }

    public Wrapper(P1 instance)
    {
        this.Instance = instance;
    }

    public int ExposedMethod()
    {
        return this.Instance.SomeMethod();
    }

    public void DoWork()
    {
        // Do something else
    }
}

此解决方案类似于外观模式http://en.wikipedia.org/wiki/Facade_pattern

于 2013-07-28T09:58:18.477 回答
0

唯一的方法,但这是一个坏方法

class Program
{
    static P1 p = new P1();
    static void Main(string[] args)
    {
        var t = new P2();
        p = t;
        ((P2)p).DoWork();
        t.DoWork();
        Console.ReadLine();
    }
}
于 2013-07-28T09:32:53.050 回答