由基类方法使用C#成员变量覆盖 [英] C# Member variable overrides used by base class method

查看:240
本文介绍了由基类方法使用C#成员变量覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

行,所以我承认右侧过顶,这是一个有点扭曲......但它确实成为一个合乎逻辑的目的。我使用C#为当前的项目,我试图找到一种方式来覆盖在派生类中的成员变量,但在基类中的方法访问被覆盖的变量。为了让事情变得更有趣这将是可取的,如果重写的成员变量是静态的(这不是在下面的示例代码所示)。

OK so I admit right off the top that this is a bit screwy … but it does serve a logical purpose. I’m using C# for a current project and I’m trying to find a way to override a member variable in a derived class, but access the overridden variable in a base class method. To make things more "entertaining" it would be preferable if the overridden member variable was static (this is NOT shown in the example code below).

下面是我的示例代码

class baseclass
{
    protected string[] array = null;

    public string method()
    {
        string str = "";
        foreach (string x in this.array)
        {
            str += x + "  "; 
        }

        return str;
    }
}

class subclass1 : baseclass
{
    new string[] array = new string[]
    {
        "class1value1",
        "class1value2",
        "class1value3",
        "class1value4"
    };
}

class subclass2 : baseclass
{
    new string[] array = new string[]
    {
        "class2value1",
        "class2value2",
        "class2value3",
        "class2value4"
    };
}



有什么想法,为什么这并不工作和方法来解决呢?

Any thoughts as to why this doesn't work and a way to get around it?

推荐答案

是否有任何理由,你不能使用一个虚拟财产?这将提供正是你正在寻找的功能。它只是不会是一个字段

Is there any reason you can't use a virtual property? That would provide exactly the functionality you are looking for. It just wouldn't be a field.

protected abstract string[] array { get; }



...

...

protected override string[] array { get { return new string[]{"...","..."}; }}

这篇关于由基类方法使用C#成员变量覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆