.NET中多重继承的替代方法是什么 [英] What is the alternative to multiple inheritance in .NET

查看:117
本文介绍了.NET中多重继承的替代方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从2GL迁移到OO时,请如下选择我的对象:
每个屏幕或数据库表都有一个类.

但是,它仍然让人联想起我在80年代学到的高度标准化的2GL.

E.G
我具有用于人员",用户",角色",功能",角色功能","UserRoles",乘客",路线",阶段","RouteStages",票证","RouteTickets"等的类.

在适当的OO世界中,人员可以坐在树的顶部,乘客和用户可以从树中继承,因为他们拥有是"标准.但是用户还需要借鉴从功能继承的角色.

同样,RouteStage类从Route和Stage继承继承方面,这就是在我们考虑故障单属性之前的原因.
然后,当用户进行购买时,可以很好地衡量乘客和机票的冲突".

我正在阅读接口-这是走的路还是这是不折腾的经典案例... ???

When I moved to OO from 2GL choose my objects as follows:
Each screen or database table got a class.

But it still reeks of the heavily normalized 2GL that I learned in the 80s.

E.G
I have classes for Persons, Users, Roles, Features, RoleFeatures, UserRoles, Passengers, Routes, Stages, RouteStages, Tickets, RouteTickets and so on.

In a proper OO world the Person can sit at the top of a tree, Passenger and User can inherit from it as they have the "Is a" criterium. But User also needs to draw from roles who inherit from Features.

Similarly the RouteStage class draws inherits aspects from both Route and Stage, and thats before we factor in Ticket Attributes.

Then for good measure Passenger and Ticket ''collide'' when the user makes a purchase.

I am reading up on Interfaces - is this the path to take or is this a classic case of its not broken... ???

推荐答案

继承接口.您可以继承一个类和多个接口.或者,您可以创建一个继承链.我想您也可以使用依赖注入来解决它.

当使用MFC(非托管C ++)时,您不能多次继承自CObject派生的任何东西.这是(现在仍然是)屁股上的皇室痛苦.
Inheriting interfaces. You can inherit one class, and multiple interfaces. Alternatively, you can create an inheritance chain. I suppose you could also use dependency injection to get around it.

When using MFC (unmanaged C++), you couldn''t multiple inherit from anything derived from CObject. It was (and still is?) a royal pain in the ass.


另一个需要关注的概念问题是"is"和"has"之间的区别:User是一个Person,而User有一些Role.因此,RoleUser的属性.对于Role,有一些User.如果将Users设置为Role的属性,则会陷入疯狂的循环.如果需要这样的东西,我会创建一个函数GetUsersForRole(Role role).
Another conceptual point to look at is the difference between "is" and "has": a User is a Person, while a User has some Roles. Consequently, Role is property of User. For a Role, there are some Users; if you make Users a property of Role, then you''d get into a crazy loop. I''d create a function GetUsersForRole(Role role) if such a thing is needed.


接口绝对是必经之路.您不应该再真正使用继承(除了接口之外),因为它会引起更多值得重视的问题.您应该进行组合,并且在需要共享功能时,将其移至可在接口上工作的服务类以完成所需的工作.这样一来,您无需继承即可获得可重用性.
Interfaces are definitely the way to go. You shouldn''t really use inheritance any more (apart from interface), as it causes more problems that it''s worth. You should go for composition and when you need shared functionality, move that to a service class that works over the interface to do what you need. That way you get re-usability without the inheritance.


这篇关于.NET中多重继承的替代方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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