如何从不同的装配体扩展模型?
如何将属性添加到在其他装配中创建的模型中。我们有许多应用程序,从桌面应用程序到 Web 应用程序,因此我有类库,其中包含所需的每个模型及其关系。我可以很容易地引用我的类库并查询需要什么。然而,由于我没有对每个表中的每个字段进行建模(某些表有超过 30 个字段)。
如何扩展原始模型以赋予其更多属性?或者我应该简单地对我正在使用的表中的所有内容进行建模?我最初的想法是,如果开发人员能够按照自己的意愿扩展任何模型来满足其项目需求,那就太好了。
How can I add a property to a model that was created in an other assembly. We have many applications ranging from desktop applications to web applications so I have class library with each model needed along with their relationships. I am very easily able to reference my class library and query what is needed. However, due to the fact that I am not modelling every field in each table (some tables have upwards of 30+ fields).
How can I extend the original model to give it more properties? Or should I simply model everything in the tables that I am using? My original thinking was that it would be nice if the developer could extend any model to his will to fit his project needs.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您有对旧程序集的引用并且该类是公共的,那么您可以从旧程序集的基类继承您自己的新程序集类。
you may inherit your own class of a new assembly form base class of old assembly if you have a reference to the old one and that class is public.
除了 Arseny 所建议的之外,您还可以通过添加所谓的扩展方法来“假冒扩展类”。作为一个例子,你可以像这样扩展字符串:
它只利用它所扩展的类上公开的内容,因此它不会违反在不拥有源代码的情况下不修改其他人的类的合同。但它添加了语法糖,让您可以调用该类,就好像您确实修改了它一样,如下所示:
In addition to what Arseny is suggesting, you may "fake extending the class" by adding so-called extension methods. As an example you could extend string like this:
Which only utilizes publicly exposed stuff on the class it's extending and so it doesn't break the contract of not modifying somebody elses class without owning the source code. But it adds syntactic sugar letting you call the class as if you had indeed modified it, like this: