代码之家  ›  专栏  ›  技术社区  ›  adam0101

如何使用CodeDom创建十进制常量?

  •  1
  • adam0101  · 技术社区  · 14 年前

        Private Sub AddBoundedValue(ByVal boundedValue As Object, ByVal type As CodeTypeDeclaration, ByVal numericType As Type, name As String)
    
            If boundedValue IsNot Nothing Then
    
                Dim constant As New CodeMemberField(numericType, name)
                constant.Attributes = MemberAttributes.Const Or MemberAttributes.Public
                constant.InitExpression = New CodePrimitiveExpression(Convert.ChangeType(boundedValue, numericType))
                type.Members.Add(constant)
    
            End If
    
        End Sub
    

    如果开发人员为“boundedValue”参数传入一个十进制值,为“numericType”参数传入十进制类型,则生成以下代码。

    Public Const DollarAmountMaximumValue As Decimal = 100000
    

    尽管传递到CodePrimitiveExpression对象的构造函数中的数据类型是十进制的,但生成的代码是一个整数,它被隐式转换并存储在十进制变量中。有没有办法让它在数字后面加上“D”来生成:

    Public Const DollarAmountMaximumValue As Decimal = 100000D
    

    1 回复  |  直到 14 年前
        1
  •  0
  •   adam0101    14 年前

    嗯,我对这个解决方案不满意,但除非有人有更好的解决方案,否则我就不得不接受。

    Private Sub AddBoundedValue(ByVal boundedValue As Object, ByVal type As CodeTypeDeclaration, ByVal numericType As Type, name As String)
    
        If boundedValue IsNot Nothing Then
    
            Dim constant As New CodeMemberField(numericType, name)
            constant.Attributes = MemberAttributes.Const Or MemberAttributes.Public
            If numericType Is GetType(Decimal) AndAlso [I detect if the language is VB.NET here] Then
                constant.InitExpression = New CodeSnippetExpression(boundedValue.ToString & "D")
            Else
                constant.InitExpression = New CodePrimitiveExpression(Convert.ChangeType(boundedValue, numericType))
            End If
            type.Members.Add(constant)
    
        End If
    
    End Sub