Workaround for VB.NET partial method using CodeDom?

蓝咒 提交于 2019-12-11 01:26:24

问题


I know CodeDom doesn't support partial methods, but is there a workaround? I found a workaround for C#, but I need one for VB.NET. Thanks.


回答1:


It is a horrible hack, as wicked as the C# one, but it does work:

Imports System.CodeDom
Imports System.CodeDom.Compiler
Imports System.IO

Module Module1

    Sub Main()
        Dim unit As New CodeCompileUnit
        Dim nspace As New CodeNamespace("SomeNamespace")
        Dim vbclass As New CodeTypeDeclaration("SomeClass")
        vbclass.IsClass = True
        Dim snippet As New CodeSnippetTypeMember("Partial _")
        vbclass.Members.Add(snippet)
        Dim method As New CodeMemberMethod()
        method.Name = "SomeMethod"
        method.Attributes = MemberAttributes.Private
        vbclass.Members.Add(method)
        nspace.Types.Add(vbclass)
        unit.Namespaces.Add(nspace)

        dim provider As CodeDomProvider = CodeDomProvider.CreateProvider("VB")
        Dim options As New CodeGeneratorOptions()
        options.BlankLinesBetweenMembers = False
        dim writer As new StringWriter()
        provider.GenerateCodeFromCompileUnit(unit, writer, options)
        Console.WriteLine(writer.ToString())
        Console.ReadLine()
    End Sub

End Module

Note that the BlankLinesBetweenMembers option is crucial to make the hack work. Output:

Option Strict Off
Option Explicit On

Namespace SomeNamespace
    Public Class SomeClass
Partial _
        Private Sub SomeMethod()
        End Sub
    End Class
End Namespace



回答2:


I ended up detecting the language and using CodeSnippetTypeMember()

Dim onDeleting = "Partial Private Sub OnDeleting()" & Environment.NewLine & "End Sub"
type.Members.Add(New CodeSnippetTypeMember(onDeleting))


来源:https://stackoverflow.com/questions/1820425/workaround-for-vb-net-partial-method-using-codedom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!