[英]Should I be using “internal” or “private” instead of “public” for methods that call other methods?
In my C# project I have methods that call other methods like this: 在我的C#项目中,我有一些方法可以像这样调用其他方法:
options = ReferenceUtilities.GetMenuStatuses();
In my ReferenceUtilities I have coded: 在我的ReferenceUtilities中,我编写了代码:
internal static SelectList GetMenuStatuses()
{
throw new NotImplementedException();
}
But should I be using internal or private? 但是我应该使用内部还是私有的? I am not sure of the difference here.
我不确定这里的区别。
As people have already answered, internal means that the member can be accesed by other code in the same assembly. 正如人们已经回答的那样,内部意味着该成员可以被同一程序集中的其他代码访问。 private means that it can be accessed from other code in the same class.
private表示可以从同一类中的其他代码访问它。
However, one important point to add: In Properties/Assemblyinfo.cs, you can add the [assembly: InternalsVisibleTo("something")] statement, that lets you access the internal methods from a different assembly. 但是,要添加的一个重要点:在Properties / Assemblyinfo.cs中,可以添加[assembly:InternalsVisibleTo(“ something”)]语句,该语句使您可以从其他程序集中访问内部方法。
This can be extremely useful for unit testing purposes, and is a good reason to sometimes use internal over private. 这对于单元测试非常有用,并且是有时使用内部而非私有的一个很好的理由。
(There is a huge debate over unit testing internals or not, but it is good to know about the possibility.) (关于是否进行内部单元测试的争论很大,但是很高兴知道这种可能性。)
internal
means that the member can be accesed by other code in the same assembly. internal
表示该成员可以被同一程序集中的其他代码访问。 private
means that it can be accessed from other code in the same class. private
表示可以从同一类中的其他代码访问它。
This has nothing to do with whether the method calls other methods. 这与该方法是否调用其他方法无关。
internal
is between assemblies while private
is between classes internal
在程序集之间,而private
在类之间
Internal means that other classes in the same assembly can see the method. 内部意味着同一程序集中的其他类可以看到该方法。 Private means only the class where the method is defined can see it.
私有意味着只有定义了方法的类才能看到它。 If the method will only ever be called by the class that defines it, use private.
如果仅由定义该方法的类调用该方法,请使用private。 Otherwise, use internal.
否则,请使用内部。 Public should only be used when classes outside the assembly need to call the method directly.
仅当程序集外部的类需要直接调用该方法时,才应使用public。
As always, there are exceptions, but this is a good general rule to live by. 和往常一样,也有例外,但这是一个很好的通用规则。
Going a bit further, service classes (ie methods that exist solely to provide a service or feature) should implement interfaces that define the contract for that service or feature. 再进一步,服务类(即仅用于提供服务或功能的方法)应实现定义该服务或功能的合同的接口。 Other classes should pass around an instance of that interface so that only the interface methods are available.
其他类应绕过该接口的实例,以便仅接口方法可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.