繁体   English   中英

访问抽象类方法C#,ASP.net

[英]Accessing Abstract Class Methods C#,ASP.net

我的程序中包含以下类,现在我想访问类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()
    {
    }
}

您将需要创建Y的实例。 由于它是abstract ,因此您必须创建它的一些子类。

public class SubY : Y
{

}

然后在您的代码中编写如下内容:

var suby = new SubY();
int r2 = suby.M2(10, 5); //15

暂无
暂无

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

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