CodeDom 生成 VB.NET 运算符重载?
有没有办法在Vb.net中使用CodeDom生成重载运算符?我想生成这个:
Public Shared Operator =(ByVal x As MyType, ByVal y As MyType) As Boolean
Return x Is y
End Operator
我能想到的最接近的黑客可以执行以下操作:
Dim eq As New CodeMemberMethod()
eq.Name = "Operator ="
eq.Parameters.Add(New CodeParameterDeclarationExpression(New CodeTypeReference("MyType"), "x"))
eq.Parameters.Add(New CodeParameterDeclarationExpression(New CodeTypeReference("MyType"), "y"))
eq.Attributes = MemberAttributes.Public Or MemberAttributes.Static
eq.ReturnType = New CodeTypeReference(GetType(Boolean))
eq.Statements.Add(New CodeMethodReturnStatement(New CodeBinaryOperatorExpression(New CodeVariableReferenceExpression("x"), CodeBinaryOperatorType.IdentityEquality, New CodeVariableReferenceExpression("y"))))
type.Members.Add(eq)
生成这个,接近但显然是错误的:
Public Shared Function Operator =(ByVal x As MyType, ByVal y As MyType) As Boolean
Return (x Is y)
End Function
Is there a way to use CodeDom to generate an overloaded operator in Vb.net? I want to generate this:
Public Shared Operator =(ByVal x As MyType, ByVal y As MyType) As Boolean
Return x Is y
End Operator
The closest hack I can think of to do this the following:
Dim eq As New CodeMemberMethod()
eq.Name = "Operator ="
eq.Parameters.Add(New CodeParameterDeclarationExpression(New CodeTypeReference("MyType"), "x"))
eq.Parameters.Add(New CodeParameterDeclarationExpression(New CodeTypeReference("MyType"), "y"))
eq.Attributes = MemberAttributes.Public Or MemberAttributes.Static
eq.ReturnType = New CodeTypeReference(GetType(Boolean))
eq.Statements.Add(New CodeMethodReturnStatement(New CodeBinaryOperatorExpression(New CodeVariableReferenceExpression("x"), CodeBinaryOperatorType.IdentityEquality, New CodeVariableReferenceExpression("y"))))
type.Members.Add(eq)
Which generates this, close but obviously wrong:
Public Shared Function Operator =(ByVal x As MyType, ByVal y As MyType) As Boolean
Return (x Is y)
End Function
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我讨厌这个解决方案,但它确实有效。
我确信正确的方法与从 CodeTypeMember 继承来定义成员,然后从 Microsoft.VisualBasic.VBCodeGenerator 继承以提供成员的实现有关,但我没有时间处理所有这些。我认为是时候从 CodeDom 切换到 T4 了。
I hate this solution, but it works.
I'm sure the correct way has something to do with inheriting from CodeTypeMember to define the member, then inheriting from Microsoft.VisualBasic.VBCodeGenerator to provide the implementation of the member, but I don't have the time to deal with all that. I think it's time to make a switch from CodeDom to T4.