Implementing interfaces in partial classes

2020-08-17 18:08发布

Consider a class which implements a lot of interfaces, would it make sense to implement each interface in a separate file using partial class definitions?

Would this be an abuse of the language feature or is it an idiom I'm unaware of?

8条回答
淡お忘
2楼-- · 2020-08-17 18:16

I think there are better ways of structuring your code than using partials in this case. There's no reference in Visual Studio that you can consult to see how many partial implementations there are for a particular class so it is easy to lose track.

Depending on how much interfaces you really mean with "a lot of interfaces" you can use regions to separate the implementations. That would be fine up until 10-15 interfaces with a total of, say, 150 functions to implement. After that, things will get messy and you will lose overview. And that's where you will benefit from other mechanisms such as inheritance, encapsulation or aggregation, and the use of services and helper classes.

But I would seriously reconsider the architecture of your code if you ever come across the need to implement 15+ interfaces....

查看更多
劫难
3楼-- · 2020-08-17 18:20

I think that you should ask yourself if having a .cs file for each interface implemented by your class would make it easier or harder to understand the code. How would you name the files?

Although I might be going out on a limb here I think I'm going to suggest that you use the much hated #region directive instead if organizing the code is your goal.

查看更多
Luminary・发光体
4楼-- · 2020-08-17 18:22

You can, yes, but that won't give you any more advantages over, say, a single file with regions. Partial classes tend to be icky because it's not immediately obvious that there is another part to it, and someone else looking at the class might miss it. I personally prefer to have everything in one place.

查看更多
三岁会撩人
5楼-- · 2020-08-17 18:22

It makes about as much sense as having constructors in one partial class file, properties in another partial class file, etc., etc.

i.e. Don't do it unless you have a good reason.

查看更多
干净又极端
6楼-- · 2020-08-17 18:26

Not an idiom I have ever heard of, but sounds like an elegant way to partition your code.

查看更多
再贱就再见
7楼-- · 2020-08-17 18:27

The only benefit is to have the various interface implementations in separate physical files.

In my opinion, this is outweighed by the downside of having your class declaration located in separate physical files.

查看更多
登录 后发表回答