0

我的程序中有以下类,现在我想访问类 Y 中存在的方法 M2()。我尝试通过创建类 Z 的对象然后使用类 X 的变量并调用 x 来访问它。 M2(10,5) 但不是 Y 类,它仍在调用 X 类中存在的方法 M2()。谢谢。

public partial class Abstract_Class : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Z z = new Z();
        int r1 = z.M2(10, 20); //gives output -20
        X x = z;
        int r2 = x.M2(10,5); //gives output 10 while I want it to print 15
    }
}
public class W
{
    public virtual int M2(int x, int y)
    {
        return x - y;
    }
}
public abstract class X : W
{
    public abstract void M1();
    public override int M2(int x, int y)
    {
        return 2*(x-y);
    }
}
public abstract class Y : X
{
    public sealed override int M2(int x, int y)
    {
        return 3 * (x - y);
    }
}
public class Z : X
{
    public override void M1()
    {
    }
}
4

1 回答 1

2

You would need to create an instance of Y. Since it's abstract, you would have to create some subclass of it.

public class SubY : Y
{

}

Then in your code write something like:

var suby = new SubY();
int r2 = suby.M2(10, 5); //15
于 2013-06-10T21:58:36.787 回答