简体   繁体   English

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

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

I have the following classes in my program and now I want to access the method M2() present in the class Y. I tried to access it by creating the object of class Z and then casting it with variable of class X and calling x.M2(10,5) but instead of class Y it is still invoking the method M2() present in the class X. Thanks. 我的程序中包含以下类,现在我想访问类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()
    {
    }
}

You would need to create an instance of Y . 您将需要创建Y的实例。 Since it's abstract , you would have to create some subclass of it. 由于它是abstract ,因此您必须创建它的一些子类。

public class SubY : Y
{

}

Then in your code write something like: 然后在您的代码中编写如下内容:

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