public void Execute() { //******Retrieve Property Values**********// //Get types Type vtype = typeof(VehicleApp); Type atype = typeof(DeveloperAttribute); //get the developerattribute attached with vehivle type DeveloperAttribute developer = (DeveloperAttribute)Attribute.GetCustomAttribute(vtype, atype); Console.WriteLine(developer.Age); Console.WriteLine(developer.Name); }
public static void Dump(MemberInfo mi) { object[] attrs = (object[])mi.GetCustomAttributes(true); foreach (object o in attrs) { DeveloperAttribute d = o as DeveloperAttribute; if (d != null) { Console.WriteLine("{2,12}\t{1,15}\t {0}", d.Name, d.CodeStatus, mi.Name); } } }
//Using the attribute data //Follow on from the developer class /// <summary> /// Prints the meta data by pulling the data in the attribute /// /// TODO: Look into using the same attribute at multiple levels, accessing the info from it then: /// https://docs.microsoft.com/en-us/dotnet/standard/attributes/retrieving-information-stored-in-attributes#retrieving-multiple-instances-of-an-attribute-applied-to-the-same-scope /// </summary> public static void GetAttribte(Type t) { DeveloperAttribute attribute = (DeveloperAttribute)Attribute.GetCustomAttribute(t, typeof(DeveloperAttribute)); if (attribute == null) { Console.WriteLine("The attribute was not found"); } else { Console.WriteLine($"\nThe name of the developer: {attribute.Name}"); Console.WriteLine($"The Developers level: {attribute.Level}"); Console.WriteLine(attribute.Reviewed ? "This code has been reviewed" : "This code has not been reviewed"); } }
public static void GetAttribute(Type t) { // Get instance of the attribute. DeveloperAttribute MyAttribute = (DeveloperAttribute)Attribute.GetCustomAttribute(t, typeof(DeveloperAttribute)); if (MyAttribute == null) { Console.WriteLine("The attribute was not found."); } else { // Get the Name value. Console.WriteLine("The Name Attribute is: {0}.", MyAttribute.Name); // Get the Level value. Console.WriteLine("The Level Attribute is: {0}.", MyAttribute.Level); // Get the Reviewed value. Console.WriteLine("The Reviewed Attribute is: {0}.", MyAttribute.Reviewed); } }