简体   繁体   English

覆盖财产

[英]Overriding a property

I'm trying to override a property in my program. 我正在尝试覆盖程序中的属性。 Here is basically what I'm trying to do : 这基本上就是我要做的事情:

class A { public int test = 7; }

class B : A { public int test = 8; }


class Program
{
    static void Main(string[] args)
    {
        A test1 = new A();
        A test2 = new B();

       Console.WriteLine(test1.test);
       Console.WriteLine(test2.test);

    }
}

This displays 7 in both case when I'd like it to display 8 in the 2nd case.... 在两种情况下,当我希望它在第二种情况下显示8时,显示7 ....

I've tried virtual and override as well as new (public new int test = 8;) But it doesn't seem to work 我尝试过虚拟和覆盖以及新的(public new int test = 8;)但它似乎不起作用

And yes I know I should use private and getters. 是的,我知道我应该使用私人和吸气剂。 I just want to know if it's possible ? 我只是想知道它是否可能?

Edit : I'm not a native C# programmer so forgive me if i mix the terms (such as field and propertys)! 编辑:我不是本地C#程序员,所以请原谅我,如果我混合使用条款(如字段和属性)!

I'm trying to override a property in my program. 我正在尝试覆盖程序中的属性。

class A { public int test = 7; }

The problem is that int test is not a property , it is a public field . 问题是int test不是属性 ,它是一个公共字段 Fields cannot be overriden. 字段无法覆盖。

Here is an example of overriding a property: 以下是覆盖属性的示例:

class A {
    public virtual int test {
        get {return 7;}
    }
}

class B : A {
    public override int test {
        get {return 8;}
    }
}

Here is a demo of this code on ideone . 以下是ideone上此代码的演示

test is a field, not a property. test是一个字段,而不是一个属性。 You must change it to a property and add the virtual modifier to allow it to be overriden in a subclass. 您必须将其更改为属性并添加virtual修饰符以允许它在子类中重写。 You must then use the override keyword to override the value returned in class B : 然后,您必须使用override关键字覆盖B类中返回的值:

class A
{
    public virtual int test
    {
        get { return 7; }
    }
}

class B : A 
{
    public override int test
    {
        get { return 8; }
    }
}

Change this 改变这个

A test2 = new B();

with this 有了这个

B test2 = new B();

If you create test2 as A you call A methods 如果将test2创建为A,则调用A方法

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

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