C# Extension Methods only visible and accessible w

2019-03-18 17:48发布

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".

2条回答
Fickle 薄情
2楼-- · 2019-03-18 18:27

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.

查看更多
看我几分像从前
3楼-- · 2019-03-18 18:27

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

namespace Extension {
    public static class ExtensionMethods {
        public static string EnumValue(this MyEnum e) {
            switch (e) {
                case MyEnum.First:
                    return "First Friendly Value";
                case MyEnum.Second:
                    return "Second Friendly Value";
                case MyEnum.Third:
                    return "Third Friendly Value";
            }
            return "Horrible Failure!!";
        }
    }
}

ClassA.cs:

using Extension;

public class ClassA{
    //Work your magic here, using the EnumValue Extension method
    //wherever you want
}

ClassB.cs

public class ClassB{
    //EnumValue is not a valid Extension Method here.
}
查看更多
登录 后发表回答