[英]How can I use CodeDom to create a decimal constant?
我的生成器中有此功能。
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
谢谢。
好吧,我对此解决方案并不满意,但是除非有人有更好的解决方案,否则我将不得不使用它。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.