C#扩展方法只是可见的,在一个类访问("私人和QUOT;) [英] C# Extension Methods only visible and accessible within one class ("private")
问题描述
是否有可能在C#中,创建一个类扩展方法,但在一个类中限制可见性/可访问性? (如扩展方法A对M级是唯一的等级Z中访问)
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)
例如:
class A
{
String foo = "";
String bar = foo.MakeMillionaire("arg");
}
在上面的例子中我想要的扩展方法MakeMillionaire扩展String类的只有的是A级中可见和可访问的我能做到这一点通过某种方式中定义的扩展方法在静态类A类?
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?
编辑:尝试定期嵌套类的产量。错误:扩展方法必须在顶级静态类中定义
Trying a regular nested class yields "Error: Extension methods must be defined in a top level static class".
推荐答案
扩展方法只能在静态非通用外(非嵌套)类中定义的。
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.
这将仍然可见于其他类的组件;避免,唯一的办法是移动消费类( A级
在你的例子),以它自己的程序集,你可能不希望做的事情。
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.
这篇关于C#扩展方法只是可见的,在一个类访问("私人和QUOT;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!