using System; using System.Reflection; [MyAttribute("Class Attribute")] class MyClass { [MyAttribute("Member Attribute")] public void MyMethod() { } } class MyAttribute : Attribute { public MyAttribute(string description) { Description = description; } public string Description { get; } } class Program { static void Main(string[] args) { Type type = typeof(MyClass); object[] classAttributes = type.GetCustomAttributes(typeof(MyAttribute), true); Console.WriteLine(((MyAttribute)classAttributes[0]).Description); MethodInfo method = type.GetMethod("MyMethod"); object[] methodAttributes = method.GetCustomAttributes(typeof(MyAttribute), true); Console.WriteLine(((MyAttribute)methodAttributes[0]).Description); } }
Class Attribute Member Attribute
using System.Reflection; class MyClass { [DefaultValue(42)] public int MyProperty { get; set; } } class DefaultValueAttribute : Attribute { public DefaultValueAttribute(object value) { Value = value; } public object Value { get; } } class Program { static void Main(string[] args) { PropertyInfo property = typeof(MyClass).GetProperty("MyProperty"); DefaultValueAttribute attribute = property.GetCustomAttribute(); int defaultValue = (int)attribute.Value; Console.WriteLine(defaultValue); } }
42This example demonstrates how to use the IAttributeSet Get method to retrieve the value of a custom attribute. Package library: The System.Reflection namespace in the .NET Framework.