抽象类中的部分方法 (C#)
我正在创建一个可以在 LINQ to SQL 类的分部类中继承的抽象类。 LINQ to SQL 类包含一堆内置的部分方法。 有没有一种方法可以实现抽象类中的一个或多个部分方法? 我知道部分方法只能包含在部分类或结构中。 我确信必须有另一种方法来做到这一点。
这里有更多细节:
- 我可能有一个名为 News 的数据库表。 如果我创建包含此表的 LINQ to SQL dbml 文件,自动生成的代码会生成 News 的分部类。
- 该分部类包含几个分部方法。
- 我正在构建一个类,其中包含我想在所有 LINQ to SQL 类中使用的几种方法。
- 其中一种方法是添加到每个 LINQ to SQL 类的部分方法。 我有一个用于此方法的通用主体。 我不是将此方法添加到每个分部类中,而是寻找一种方法来创建它一次并通过我的基类继承来继承它。
希望有助于解释更多。
I'm creating an abstract class that can be inherited in a partial class of a LINQ to SQL class. The LINQ to SQL class contains a bunch of built-in partial methods. Is there a way that I can implement one or more of the partial methods in the abstract class? I know that partial methods can only be contained within partial classes or structs. I'm sure there's got to be another way to do it.
Here's more detail:
- I may have a database table called News. If I create a LINQ to SQL dbml file containing this table, the auto-generated code generates a partial class for News.
- This partial class contains several partial methods.
- I have a class that I'm building that contains several methods that I'd like to use across all my LINQ to SQL classes.
- One of these methods is a partial method added to each LINQ to SQL class. I have a common body to use for this method. Rather than adding this method to each partial class, I'm looking for a way to create it once and inherit it with my base class inheritance.
Hope that helps explain more.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
部分方法不能通过继承使用。 您可以将常规方法添加到抽象基类,但它们不会自动与部分方法声明“配对”。 所以不行。 当然,您可以简单地将部分方法实现调用到基类中。
另请注意,如果通用代码与审核(谁/何时)等相关,您还可以通过重写
DataContext
的SubmitChanges
方法并调用GetChangeSet
:最后,请注意,您还可以为 dbml 中的所有实体指定一个公共基类(像这样); 您不必在每个部分类中手动完成此操作。
Partial methods are not usable over inheritance. You could add regular methods to the abstract base class, but they won't automatically "pair" with the partial method declarations. So: no. You can, of course, simply have the partial method implementation call into the base-class.
Note also that if the common code relates to things like audit (who/when), you can also do this by overriding the
DataContext
'sSubmitChanges
method, and callingGetChangeSet
:Finally, note that you can also specify a common base-class for all your entities in the dbml (like so); you don't have to do it by hand in each partial class.
我想我明白你想做什么,但如果不明白,请告诉我。 您可以将抽象基类部分化,并将所需的实现拉到该类中。 或者,您可以采用抽象类并封装您希望子类访问的功能。
I think I understand what you want to do, but if not, let me know. You can make your abstract base class partial and pull the implementation you want up into that class. Alternatively, you could take your abstract class and encapsulate the functionality you want your child classes to have access to.