Creating an extension method using CodeDOM

I am trying to create an extension method using CodeDOM. There seems to be no support for them, and use ExtensionAttribute(which C # uses internally to indicate extension methods) is not allowed.

You can use the trick to specify a modifier this, but how can I make the containing class staticso that the code really compiles?

Since it staticis a C # concept, it is not displayed through the CodeDOM API. And setting TypeAttributesin TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.Publicdoes not work because

abstract class cannot be sealed or static

How do I compile an extension method?

+3
source share
4

, :

var staticClass = new CodeTypeDeclaration("Extensions")
    {
        Attributes = MemberAttributes.Public|MemberAttributes.Static
    };

, , . :

provider.Supports(GeneratorSupport.StaticConstructors);
// True

provider.Supports(GeneratorSupport.PublicStaticMembers);
// True

, , , , Attributes 0x00005002 0x00006003.

Microsoft Connect :

. , , CodeDom.

, CodeDom , , , . #, VB . , , #, VB, .

, , .


:

var type = new CodeTypeDeclaration("Extensions");
type.Attributes = MemberAttributes.Public;
type.StartDirectives.Add(
    new CodeRegionDirective(CodeRegionMode.Start, "\nstatic"));
type.EndDirectives.Add(
    new CodeRegionDirective(CodeRegionMode.End, String.Empty));

:

#region
static
public class Extensions
{
}
#endregion

.

+6

, : , .

public static void MarkAsStaticClassWithExtensionMethods(this CodeTypeDeclaration class_)
{
   class_.Attributes = MemberAttributes.Public;

   class_.StartDirectives.Add(new CodeRegionDirective(
           CodeRegionMode.Start, Environment.NewLine + "\tstatic"));

   class_.EndDirectives.Add(new CodeRegionDirective(
           CodeRegionMode.End, string.Empty));
}
+2

, CodeCompileUnit, , class Extensions static class Extensions .

+1

You can get your code to compile exactly how you want it, converting it directly to a string, and then hacking it:

    private static CodeSnippetTypeMember CreateStaticClass(CodeTypeDeclaration type)
    {
        var provider = CodeDomProvider.CreateProvider("CSharp");
        using (var sourceWriter = new StringWriter())
        using (var tabbedWriter = new IndentedTextWriter(sourceWriter, "\t"))
        {
            tabbedWriter.Indent = 2;
            provider.GenerateCodeFromType(type, tabbedWriter, new CodeGeneratorOptions()
            {
                BracingStyle = "C",
                IndentString = "\t"
            });
            return new CodeSnippetTypeMember("\t\t" + sourceWriter.ToString().Replace("public class", "public static class"));
        }
    }
0
source

All Articles