167. Custom Attribute

ראינו פעמים קודמות דוגמאות לAttributeים מהFramework.

באופן דומה, אנחנו יכולים ליצור Attribute משלנו. Attribute כזה נקרא Custom Attribute.

כדי לעשות זאת עלינו לרשת מהמחלקה Attribute.

הקונבנציה היא שהשם של המחלקה יסתיים במילה Attribute, למרות שזה לא חובה.

אז הנה:

1
2
3
4
public class PeanutAttribute : Attribute
{
// ...
}

עכשיו נוכל להצמיד אותו לMember/Typeים שלנו:

1
2
3
4
5
6
7
8
9
10
[PeanutAttribute()]
public void SomeMethod(int givenNumber, string givenString)
{
}
[Peanut]
public class MyClass
{
// ..
}

שימו לב שבגלל שהAttribute שלנו עונה על הקונבנציה, אנחנו פטורים מכתיבת המילה Attribute (ראו גם טיפ מספר 164)

נוכל גם לשים לו Properties משלנו או Constructor לא דיפולטי:

1
2
3
4
5
6
7
8
9
10
11
12
public class PeanutAttribute : Attribute
{
private string Description { get; set; }
private int Length { get; set; }
public PeanutAttribute(string description, int length)
{
Description = description;
Length = length;
}
// ...
}

ואז נוכל לשים את הAttribute בצורה הבאה:

1
2
3
4
5
6
7
8
9
10
[PeanutAttribute("This method does something", 3)]
public void SomeMethod(int givenNumber, string givenString)
{
}
[Peanut("My class is the best class", 10)]
public class MyClass
{
// ..
}

ואם יש לנו Properties שהם public נוכל גם אותם לאתחל בAttribute:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class PeanutAttribute : Attribute
{
private string Description { get; set; }
private int Length { get; set; }
public string Address { get; set; }
public PeanutAttribute(string description, int length)
{
Description = description;
Length = length;
}
// ...
}

למשל

1
2
3
4
5
[Peanut("My class is the best class", 10, Address ="http://en.wikipedia.org/wiki/MyClass")]
public class MyClass
{
// ..
}

עד כאן החגיגה…


למרבה הצער, יש גם מספר מגבלות במחלקות שהן Attributeים. ראשית, הן לא יכולות להיות גנריות.

שנית, לא נוכל לאתחל בConstructor (או בעזרת Property) טיפוס שהוא לא מהצורה הבאה:

  • Primitive – כלומר bool, byte, char,double, float, int, long, short, string
  • Enum
  • Type – אותו נאתחל באמצעות typeof
  • מערך חד מימדי מאחד הסוגים מעלה

שבוע בר סגולה טוב

שתף