Nota: questo è un follow-up di un answer su un previous question.Utilizzare la riflessione per ottenere l'attributo di una proprietà tramite il metodo chiamato dal setter
Sto decorando il setter di una proprietà con un attributo chiamato TestMaxStringLength
utilizzato nel metodo chiamato dal setter per la convalida.
L'immobile attualmente si presenta così:
public string CompanyName
{
get
{
return this._CompanyName;
}
[TestMaxStringLength(50)]
set
{
this.ValidateProperty(value);
this._CompanyName = value;
}
}
ma vorrei piuttosto simile a questa:
[TestMaxStringLength(50)]
public string CompanyName
{
get
{
return this._CompanyName;
}
set
{
this.ValidateProperty(value);
this._CompanyName = value;
}
}
Il codice per ValidateProperty
che è responsabile per la ricerca degli attributi del setter è :
private void ValidateProperty(string value)
{
var attributes =
new StackTrace()
.GetFrame(1)
.GetMethod()
.GetCustomAttributes(typeof(TestMaxStringLength), true);
//Use the attributes to check the length, throw an exception, etc.
}
Come modificareCodiceper cercare gli attributi nella proprietà anziché set?
Ooh. Mi piace molto questo approccio da una prospettiva di codifica. Ovviamente, la decorazione degli attributi è inutile a meno che non venga implementata la validazione, il che è un po 'più difficile da assumere in questo modello, ma nel complesso dovrebbe essere più veloce e più pulito. –
potresti dirmi come convalidare il valore rispetto a atts? Grazie! – VladL