Mega Code Archive

 
Categories / C# / Reflection
 

Attribute IsDefaultAttribute

using System;     using System.Reflection;     public enum Animal      {         Dog = 1,         Cat,         Bird,     }     public class AnimalTypeAttribute : Attribute      {         public AnimalTypeAttribute(Animal pet)          {             thePet = pet;         }         public AnimalTypeAttribute()          {             thePet = Animal.Dog;         }         protected Animal thePet;         public Animal Pet          {             get { return thePet; }             set { thePet = Pet; }         }         public override bool IsDefaultAttribute()          {             if (thePet == Animal.Dog)                 return true;             return false;         }     }     public class TestClass      {         [AnimalType]         public void Method1()         {}     }     class DemoClass      {         static void Main(string[] args)          {             Type clsType = typeof(TestClass);             MethodInfo mInfo = clsType.GetMethod("Method1");             AnimalTypeAttribute atAttr = (AnimalTypeAttribute)Attribute.GetCustomAttribute(mInfo,typeof(AnimalTypeAttribute));             Console.WriteLine("The attribute {0} for method {1} in class {2}",atAttr.Pet, mInfo.Name, clsType.Name);              Console.WriteLine("{0} the default for the AnimalType attribute.",atAttr.IsDefaultAttribute() ? "is" : "is not");         }     }