168. GetCustomAttributes

בפעם הקודמת ראינו כיצד אנחנו יכולים ליצור Attribute משלנו ולקשט את הקוד שלנו בעזרתו.

כדי שלAttribute תהיה השפעה על איך הקוד שלנו מתנהג, נוכל להשתמש בפונקציה GetCustomAttributes של MemberInfo (ראו גם טיפ מספר 161):

לדוגמה, אם נמשיך עם הטיפוסים מהדוגמה של אתמול:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
MemberInfo myClassType = typeof(MyClass);
object[] attributes =
myClassType.GetCustomAttributes(true);
foreach (Attribute currentAttribute in attributes)
{
PeanutAttribute peanutAttribute =
currentAttribute as PeanutAttribute;
if (peanutAttribute != null)
{
Console.WriteLine(peanutAttribute.Address);
Console.WriteLine(peanutAttribute.Description);
Console.WriteLine(peanutAttribute.Length);
}
}
// http://en.wikipedia.org/wiki/MyClass
// My class is the best class
// 10

באופן דומה, מאחר וגם MethodInfo, PropertyInfo יורשים מMemberInfo, נוכל להריץ את פונקציה זו עליהן, למשל:

1
2
3
4
[PeanutAttribute("This method does something", 3)]
public void SomeMethod(int givenNumber, string givenString)
{
}

הרצת הקוד תניב את התוצאות הבאות:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
MethodInfo someMethodInfo =
typeof(MyType).GetMethod("SomeMethod");
object[] attributes =
someMethodInfo.GetCustomAttributes(true);
foreach (Attribute currentAttribute in attributes)
{
PeanutAttribute peanutAttribute =
currentAttribute as PeanutAttribute;
if (peanutAttribute != null)
{
Console.WriteLine(peanutAttribute.Address);
Console.WriteLine(peanutAttribute.Description);
Console.WriteLine(peanutAttribute.Length);
}
}
//
// This method does something
// 3

(אם אתם לא זוכרים כיצד משיגים MethodInfo, תוכלו לקרוא את טיפ מספר 147)

בעצם, מה שקורה כאן זה שהוספנו Metadata משלנו.

כעת נשאר להשתמש בכלי זה בחוכמה כדי לעשות דברים יפים 😃

נראה דוגמאות בהמשך.

המשך יום בר סגולה

שתף