C#: Extending from more than 1 class

我与影子孤独终老i 提交于 2020-01-03 13:03:24

问题


Suppose I have a ViewModel TabViewModel that Extends ObservableObject the class for ViewModels in the MVVM Foundation Framework. Then I also have a EditorTabViewModel that extends TabViewModel, Now I need to extend DependencyObject to implement DependencyProperties. I cannot extend more than 1 class. How might I implement this? I could have an "intermediate" class like ...

TabViewModel : ObservableObject

EditorTabViewModel : TabViewModel

DependentEditorTabViewModel : DependencyObject

but thats 1 extra unnecessary class. Any better way to do this?

UPDATE

Ops actually I cant do the above. DependentEditorTabViewModel still need to extend EditorTabViewModel ... apart from DependencyObject


回答1:


C# does not support Multiple Inheritance. Your best bet is to use Interfaces, rather than parent classes.

Even if you don't have the option of using interfaces (maybe you don't have access to the code), it's generally better to prefer composition over inheritance. Do you really need to inherit both of these classes, or can you compose with them instead?




回答2:


Its not an extra class if you're accomplishing what you need. Here is how you would go about that:

DependentEditorTabViewModel : DependencyObject

TabViewModel : DependentEditorTabViewModel


来源:https://stackoverflow.com/questions/3951709/c-extending-from-more-than-1-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!