由基类方法使用C#成员变量覆盖

编程入门 行业动态 更新时间:2024-10-23 22:37:18
本文介绍了由基类方法使用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#成员变量覆盖

本文发布于:2023-07-29 08:47:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1239204.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   成员   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!