C# - 当每个继承的类都需要来自基类的 getter 而只需要一个继承类的 setter 时,我该怎么办 [英] C# - What should I do when every inherited class needs getter from base class, but setter only for ONE inherited class

查看:18
本文介绍了C# - 当每个继承的类都需要来自基类的 getter 而只需要一个继承类的 setter 时,我该怎么办的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 WizardViewModelBase 的抽象类.

I have a abstract class called WizardViewModelBase.

我所有的 WizardXXXViewModel 类都继承自基础抽象类.

All my WizardXXXViewModel classes inherit from the base abstract class.

base 有一个带有 getter 的属性.每个子类都需要并覆盖该字符串

The base has a property with a getter. Every sub class needs and overrides that string

属性作为 ViewModel 的 DisplayName.

property as its the DisplayName of the ViewModel.

只有一个名为 WizardTimeTableWeekViewModel 的 ViewModel 需要一个 setter,因为我必须设置

Only ONE ViewModel called WizardTimeTableWeekViewModel needs a setter because I have to set

ViewModel 是 A 周还是 B 周的时间表.使用 2 个 ViewModel,例如

wether the ViewModel is a timetable for week A or week B. Using 2 ViewModels like

WizardTimeTableWeekAViewModel 和 WizardTimeTableWeekBViewModel 将是多余的.

WizardTimeTableWeekAViewModel and WizardTimeTableWeekBViewModel would be redundant.

我不想覆盖所有其他类中的 setter,因为它们不需要 setter.

I do not want to override the setter in all other classes as they do not need a setter.

我能以某种方式告诉子类它不需要覆盖 setter 吗?

Can I somehow tell the sub class it needs not to override the setter?

或者任何其他建议?

有了接口,我可以自由地使用 getter 或 setter,但有很多空的 setter

With interfaces I would be free to use getter or setter but having many empty setter

属性不是我的选择.

有趣.. 我只是想如果我真的需要设置 WizardPages 的所有 DisplayNames 会发生什么,这与我首先说的相反.也许我不应该因为本地化而对 getter 中的字符串进行硬编码并将字符串放在资源文件中,然后我需要在每个子类中的任何地方都有一个 setter XD

Funny.. I have just thought what would happen if I really would need to SET all DisplayNames of the WizardPages contrary what I said firstly. Maybe I should not hardcode the strings in the getter and put the strings in a reesource file because of localization, then I need a setter anywhere in every sub class XD

推荐答案

不要将 setter 方法声明为虚拟方法.

Don't declare the setter method as virtual.

如果出于某种原因(我想不出一个!)你需要它在继承层次结构的顶部是虚拟的,那么在覆盖它时使用密封:

If for some reason (I can't think of one!) you need for it to be virtual at the top of your inheritance hierarchy then use sealed when you override it:

http://msdn.microsoft.com/en-us/library/aa645769(VS.71).aspx

这篇关于C# - 当每个继承的类都需要来自基类的 getter 而只需要一个继承类的 setter 时,我该怎么办的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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