I'm having a hard time trying to figure out the meaning of this advice from Attribute Usage Guildelines:
Do not define a parameter with both named and positional arguments. The following code example illustrates this pattern.
And the code is:
public class NameAttribute: Attribute
{
string userName;
int age;
// This is a positional argument.
public NameAttribute (string userName)
{
this.userName = userName;
}
public string UserName
{
get
{
return userName;
}
}
// This is a named argument.
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
}
Now, I'm sorry if it's really simple and I am wasting your time. But I just don't understand the meaning and what example demonstrates. The fact that English is not my native language might be a factor, but I didn't experience any difficulties reading MSDN before. I also tried to read the translated version of this a开发者_如何学Pythonrticle, but it makes even less sense to me.
So, if someone would be kind enough to rephrase and explain it to me, that would be really helpful. If you can also explain why MSDN advises to do so, I'm all ears.
Think about how you would have to use such an attribute:
[Name("Jack", Age = 25)]
public class ClassToDecorate { }
Now, this doesn't look all that clear because two styles are being mixed: UserName
is being set via the attribute's constructor ("positional"), but Age
is being explicitly set as a property ("named").
The guideline is suggesting that it would be better to redesign the attribute such that exactly one of the following decorations would work:
[Name("Jack", 25)] // Positional only
(or)
[Name(UserName = "Jack", Age = 25)] // Named only
I think you are the victim of a crummy example, it doesn't actually demonstrate the problem. A better example of doing it wrong is adding this constructor:
public NameAttribute (string userName, int age)
{
this.userName = userName;
this.Age = age;
}
Now the client code could use the attribute this way:
[Name("foo", 42)]
and this way:
[Name("foo", Age = 42)]
Both are equally valid, the client programmer won't be able to make up his mind which one to choose. A much nastier example would be this constructor:
public NameAttribute(int age) {
this.userName = "unspecified";
this.Age = age;
}
which allows:
[Name(42, Age = 43)]
精彩评论