C# - 当每个继承类需要从基类中获取getter时,我应该做什么,但是只为一个继承类设置setter [英] C# - What should I do when every inherited class needs getter from base class, but setter only for ONE inherited class

查看:169
本文介绍了C# - 当每个继承类需要从基类中获取getter时,我应该做什么,但是只为一个继承类设置setter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类叫做WizardViewModelBase。



所有的WizardXXXViewModel类都继承自基本的抽象类。



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



属性作为其ViewModel的DisplayName。



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



因为ViewModel是A周或B周的时间表。使用2 ViewModels像



WizardTimeTableWeekAViewModel和WizardTimeTableWeekBViewModel将是多余的。



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

我能以某种方式告诉子类它不需要重写setter?



还是其他建议? / p>

对于接口,我可以自由使用getter或setter,但是有很多空的setter



属性不是一个选项对我来说。



有趣的是,我刚刚想到如果我真的需要设置所有的显示名称的WizardPages与我说的第一个相反。也许我不应该在getter中硬编码字符串,并将字符串放在一个reesource文件,因为本地化,然后我需要一个setter在每个子类XD

$任何地方

解决方案

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



如果由于某种原因(我不能想到一个!它虚拟在你的继承层次结构的顶部,然后在覆盖它时使用sealed:



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


I have a abstract class called WizardViewModelBase.

All my WizardXXXViewModel classes inherit from the base abstract class.

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

property as its the DisplayName of the ViewModel.

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

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

WizardTimeTableWeekAViewModel and WizardTimeTableWeekBViewModel would be redundant.

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

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

Or any other suggestion?

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

properties is not an option for me.

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

解决方案

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天全站免登陆