Adding Attributes to C# Property set parameter
Right now, without using properties, I've got this:
public void SetNumber([Array(new int[]{8})] Byte[] number)
As you can see, I am adding the ArrayAttribute
attribute to the parameter.
What I want to do is the same but on a property setter. This doesn't work:
[Array(new int[]{8})]
public Byte[] SetNumber
{
set
{
}
get
{
return null;
}
}
Is there any way of attaching the attribute to the set_SetNumber
value
method parameter?
Also, a related question. Th开发者_运维知识库e two methods generated (the get/set) don't have the custom attribute. Can anyone explain to me why is that?
You need to use the param
attribute target on the set
:
public Byte[] SetNumber {
[param: Array(new int[] { 8 })]
set {
}
get {
return null;
}
}
As for the second question, the custom attribute is set on the property itself, not on the property accessor methods.
Also, if your ArrayAttribute
only ever applies to parameters, it could be defined like this:
[AttributeUsage(AttributeTargets.Parameter)]
public class ArrayAttribute : Attribute {
// ...
}
You dont do that, create a method just as you have done in the first example. You cant pass anything other than value to the set.
public Byte[] TheNumber
{
private set;
get
{
return null;
}
}
public void SetNumber([Array(new int[] { 8 })] Byte[] number)
{
this.TheNumber = number;
}
I'm not certain, but my guess is that you can't do what you want - the setter value
parameter isn't exposed for you to apply an attribute to.
And as for your second question, a property is distinct from it's getter & setter methods. You can apply an attribute to the setter method like so:
public Byte[] SetNumber
{
[Array(new int[]{8})]
set
{
}
get
{
return null;
}
}
精彩评论