我的生成器中有这个功能。
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
感谢。
答案 0 :(得分:0)
嗯,我对这个解决方案并不满意,但除非有人有更好的解决方案,否则我将不得不接受它。
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