|
1 |
| -// See https://aka.ms/new-console-template for more information |
2 |
| -Console.WriteLine("Hello, World!"); |
| 1 | +using System.Reflection; |
| 2 | + |
| 3 | +Console.WriteLine(); |
| 4 | + |
| 5 | +//Getting all the types that have the CustomAttribute |
| 6 | +Assembly assembly = Assembly.GetExecutingAssembly(); |
| 7 | +var types = assembly |
| 8 | + .GetTypes() |
| 9 | + .Where(t => t.GetCustomAttribute<CustomAttribute>() is not null) |
| 10 | + .ToList(); |
| 11 | + |
| 12 | +foreach (var type in types) |
| 13 | +{ |
| 14 | + var myAttribute = type.GetCustomAttribute<CustomAttribute>(); |
| 15 | + Console.WriteLine($"{type.Name} - {myAttribute.MyProperty}"); |
| 16 | +} |
| 17 | +Console.WriteLine(); |
| 18 | +#region Creating a custom attribute |
| 19 | + |
| 20 | +[AttributeUsage(AttributeTargets.Class)] |
| 21 | +class CustomAttribute : Attribute |
| 22 | +{ |
| 23 | + //Only properties can be accesed in the attribute |
| 24 | + public int MyProperty { get; set; } |
| 25 | + public int MyProperty2 { get; set; } |
| 26 | + |
| 27 | + public CustomAttribute(int i) |
| 28 | + { |
| 29 | + |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +[CustomAttribute(5, MyProperty = MyField, MyProperty2 =50)] // OK, there is no need to write the word Attribute, compiler will add it automatically |
| 34 | +class CustomClass |
| 35 | +{ |
| 36 | + private const int MyField = 5; // Only constant values can be assigned to the attribute's properties |
| 37 | + //[Custom] // Gives error because CustomAttribute only can be applied to classes |
| 38 | + public void Method() |
| 39 | + { |
| 40 | + Console.WriteLine("Method"); |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +[Custom(5, MyProperty = 5)] |
| 45 | +public class MyClass |
| 46 | +{ |
| 47 | + |
| 48 | +} |
| 49 | + |
| 50 | +[Custom(5, MyProperty =10)] |
| 51 | +public class MyClass2 |
| 52 | +{ |
| 53 | + |
| 54 | +} |
| 55 | + |
| 56 | +public class MyClass3 |
| 57 | +{ |
| 58 | + |
| 59 | +} |
| 60 | +#endregion |
| 61 | + |
| 62 | +#region Generic Attributes |
| 63 | + |
| 64 | +[AttributeUsage(AttributeTargets.All)] |
| 65 | +class MyAttribute<T> : Attribute |
| 66 | +{ |
| 67 | + public T Value { get; set; } |
| 68 | + |
| 69 | +} |
| 70 | + |
| 71 | +[MyAttribute<int>(Value = 5)] |
| 72 | +class MyClass4 |
| 73 | +{ |
| 74 | + |
| 75 | +} |
| 76 | + |
| 77 | +#endregion |
0 commit comments