C# 扩展方法仅在一个类中可见和可访问(“私有”)
在 C# 中,是否可以在类上创建扩展方法,但限制类内的可见性/可访问性? (例如,类 M 上的扩展方法 A 只能在类 Z 中访问)
示例:
class A
{
String foo = "";
String bar = foo.MakeMillionaire("arg");
}
在上面的示例中,我希望扩展 String 类的扩展方法“MakeMillionaire”仅在类 A 中可见和可访问。我通过在类 A 内的静态类中定义扩展方法来以某种方式做到这一点?
编辑:尝试常规嵌套类会产生“错误:扩展方法必须在顶级静态类中定义”。
Is it possible, in C#, to create extension methods on a class but restrict visibility/accessibility within a class? (e.g. Extension Method A on class M is only accessible within class Z)
Example:
class A
{
String foo = "";
String bar = foo.MakeMillionaire("arg");
}
In above example I want the extension method "MakeMillionaire" extending the String class only to be visible and accessible within class A. Can I do this somehow by defining the extension method in a static class within class A?
Edit: Trying a regular nested class yields "Error: Extension methods must be defined in a top level static class".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
扩展方法只能在静态非泛型外部(非嵌套)类中定义。
在这种情况下,我通常做的是在同一文件的不同命名空间中创建一个单独的静态内部类,然后仅在该文件中包含该命名空间。
该程序集中的其他类仍然可以看到它;避免这种情况的唯一方法是将使用类(示例中的
class A
)移动到它自己的程序集中,您可能不想这样做。Extension methods can only be defined in a static non-generic outer (non-nested) class.
What I usually do in such scenarios is make a separate static internal class in a different namespace in the same file, then include that namespace only in that file.
It would still be visible to other classes in that assembly; the only way to avoid that is to move the consuming class (
class A
in your example) to its own assembly, which you probably don't want to do.在单独的命名空间中声明扩展方法,然后可以将该命名空间包含在要使用它们的特定文件中。然后,在单独的文件中声明 ClassA(要在其中使用扩展方法的类),并在 ClassA.cs 顶部使用该命名空间。这样,只有该类才能访问这些扩展方法。
编辑:
类似于以下内容
ClassA.cs:
ClassB.cs
Declare your Extension Methods in a separate namespace, and you can include that namespace in specific files that you want to use them. Then, declare ClassA (the class you want to use your extension methods in) in a separate file, and use that namespace at the top of ClassA.cs. That way, only that class will have access to those extension methods.
Edit:
Something like the following
ClassA.cs:
ClassB.cs