我开始使用以下方法分组来使我的代码更具可读性:
public interface IUserMethodGroup
{
void SomeMethodOne();
String SomeMethodTwo();
}
//File MainClass.Users.cs
public partial class MainClass : IUserMethodGroup
{
void IUserMethodGroup.SomeMethodOne(){ //some code }
String IUserMethodGroup.SomeMethodTwo(){ return "some str";}
}
//File MainClass.cs
public partial class MainClass
{
//HOW ABOUT PERFORMANCE?
public IUserMethodGroup UserHandle {get { return this; } }
}
Run Code Online (Sandbox Code Playgroud)
它对性能有很大影响吗?
编辑1
这允许我这样做:
class ConsumerClass
{
public void Method()
{
MainClass mc = new MainClass();
mc.UserHandle.SomeMethodOne();
//@ vc 74:
//Interface has to be explicitly, otherwise it will be:
ms.SomeMethodOne(); //grouping lost...
}
}
Run Code Online (Sandbox Code Playgroud)
@adelphus:考虑我有5个类似的属性(方法组).每次我想使用组中的一些方法,我都要求类返回自己.与没有群组的实施相比,它会慢得多吗?
每次我想使用组中的某些方法时,我都会要求类返回自身。与没有团体的情况下实施相比,是否要慢很多?
不。返回this只读属性应该只是一行 IL 代码。事实上,甚至可以由 JIT 优化器内联。
更大的问题是为什么一个类有这么多方法?拥有如此多的方法,需要通过显式接口实现来“组织”它们,这听起来就像您有一个做得太多的类。
这种设计确实允许您拥有实现不同“组”的不同类。然后,您的单个类将成为一个聚合器,它将多个不同接口的功能组合到一个类中。