VB中特性构造函数是否支持命名参数?语法疑问求助
VB Attribute Constructor Named Parameters: What’s Wrong With Your Syntax?
Great question—you’re right that VB does support named parameters for attribute constructors, but there’s a tiny syntax gotcha specific to attributes that’s tripping you up here. Let’s break this down:
1. Constructor Named Parameters vs. Attribute Property Initialization
First, let’s clarify two separate things in your attribute declaration:
- Constructor parameters: Your
FullNameattribute’s constructor takesFirstNameandLastName. Using:=for these (likeLastName:="moreno") is totally valid—this is how you specify named parameters for the constructor, just like you do when instantiating a regular object. - Attribute properties: The
Heyproperty is a separate member of your attribute class. For setting properties in attribute declarations, VB uses=instead of:=. The:=syntax is only for constructor arguments; property initialization in attributes uses the standard assignment operator.
2. Fixed Version of Your Code
The mistake is in how you’re setting the Hey property. Here’s the corrected attribute line:
<FullName(LastName:="moreno", FirstName:="John", Hey = "joe")> Public Class Example Public Sub Test() ' This part is already correct! Dim x = New FullName(LastName:="moreno", FirstName:="john") End Sub End Class
Your direct object instantiation (New FullName(...)) works because that’s standard VB syntax where := works for constructor named parameters. Attributes have their own rules for property initialization, which is why you need to switch to = there.
3. Quick Recap
- Use
ParameterName:=Valuefor constructor arguments in attribute declarations. - Use
PropertyName=Valuefor setting attribute properties in the same declaration.
内容的提问来源于stack exchange,提问作者jmoreno
相关产品推荐
相关产品推荐

