使用Codedom编写VB.Net属性

时间:2009-04-17 09:18:48

标签: .net vb.net codedom

查看MSDN上的示例代码:

这个

    ' Declares a type.
    Dim type1 As New CodeTypeDeclaration("Type1")

    ' Declares a constructor.
    Dim constructor1 As New CodeConstructor
    constructor1.Attributes = MemberAttributes.Public
    type1.Members.Add(constructor1)

    ' Declares an integer field.
    Dim field1 As New CodeMemberField("System.Int32", "integerField")
    type1.Members.Add(field1)

    ' Declares a property.
    Dim property1 As New CodeMemberProperty
    property1.Name = "integerProperty"
    property1.Type = New CodeTypeReference(GetType(Integer))
    ' Declares a property get statement to return the value of the integer field.
    property1.GetStatements.Add(New CodeMethodReturnStatement(New CodeFieldReferenceExpression(New CodeThisReferenceExpression, "integerField")))
    ' Declares a property set statement to set the value to the integer field.
    ' The CodePropertySetValueReferenceExpression represents the value argument passed to the property set statement.
    property1.SetStatements.Add(New CodeAssignStatement(New CodeFieldReferenceExpression(New CodeThisReferenceExpression, "integerField"), New CodePropertySetValueReferenceExpression))
    type1.Members.Add(property1)

    Dim dump As New VBCodeProvider
    Dim gen As Compiler.ICodeGenerator = dump.CreateGenerator
    Dim opt As New Compiler.CodeGeneratorOptions

    gen.GenerateCodeFromType(type1, Console.Out, opt)

应生成

Public Class Type1

   Private integerField As Integer

   Public Sub New()
       MyBase.New()
   End Sub

   Private Property integerProperty() As Integer
       Get
           Return Me.integerField
       End Get
       Set(ByVal Value As Integer)
           Me.integerField = value
       End Set
   End Property
End Class

但是我没有看到它为Set方法生成参数,即。我明白了:

       Set
           Me.integerField = value
       End Set

鉴于我已经不得不在示例代码中添加位以实际命名属性以匹配其示例输出,我怀疑有一个细节缺失导致了这一点,但我似乎无法跟踪它?虽然代码编译,但我无法在不手动添加参数的情况下使用属性,这在某种程度上违背了目的。知道缺少什么吗?

1 个答案:

答案 0 :(得分:0)

this DevCity article上的评论#3表明它无关紧要,但我知道Reflector的行为与您期望的一样,尽管可能拥有它自己代码生成的实现......