Attributes provide an efficient method for associating declarative information with C # code (types, methods, properties, etc.). An attribute associated with a program entity may be requested at runtime using a method called reflection.
© MSDN, http://msdn.microsoft.com/ru-ru/library/z0w1kczw.aspx
')
Reflection (reflection) is used to dynamically create an instance of a type, bind a type to an existing object, as well as get a type from an existing object and dynamically invoke its methods or access its fields and properties.
© MSDN, http://msdn.microsoft.com/ru-ru/library/ms173183.aspx
Extension methods allow you to “add” methods to existing types without creating a new derived type, recompiling or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods in the extended type.
© MSDN, http://msdn.microsoft.com/ru-ru/library/bb383977.aspx
public enum Womans
{
[Age(25)]
[Weight(54.5)]
Masha,
[Age(32)]
[Weight(102.5)]
Lena,
[Age(44)]
[Weight(77.4)]
Ira,
[Age(28)]
[Weight(63.75)]
Fekla
}
public enum Status
{
[RussianName( "" )]
Opened = 100,
[RussianName( "" )]
Closed = 200,
[RussianName( "- " )]
AnythingElse = 500
}
double iraWeight = Womans.Ira.GetWeight();
int lenaAge = Womans.Lena.GetAge();
string closedName = Status.Closed.GetRussianName();
public abstract class BaseAttribute : Attribute
{
private readonly object _value;
public BaseAttribute( object value ) { this ._value = value ; }
public object GetValue() { return this ._value; }
}
public static class EnumAttributesBaseLogic
{
public static VAL GetAttributeValue<ENUM, VAL>( this ENUM enumItem, Type attributeType, VAL defaultValue)
{
var attribute = enumItem.GetType().GetField(enumItem.ToString()).GetCustomAttributes(attributeType, true )
.Where(a => a is BaseAttribute)
.Select(a => (BaseAttribute)a)
.FirstOrDefault();
return attribute == null ? defaultValue : (VAL)attribute.GetValue();
}
}
public class Weight : BaseAttribute { public Weight( double value ) : base ( value ) { } }
public static double GetWeight( this Enum enumItem)
{
return enumItem.GetAttributeValue( typeof (Weight), 0m);
}
using System;
namespace EnumAttributesDemo
{
public class Age : BaseAttribute { public Age( int value ) : base ( value ) { } }
public class Weight : BaseAttribute { public Weight( double value ) : base ( value ) { } }
public class RussianName : BaseAttribute { public RussianName( string value ) : base ( value ) { } }
public static class EnumExtensionMethods
{
public static int GetAge( this Womans enumItem)
{
return enumItem.GetAttributeValue( typeof (Age), 0);
}
public static double GetWeight( this Womans enumItem)
{
return enumItem.GetAttributeValue( typeof (Weight), 0d);
}
public static string GetRussianName( this Status enumItem)
{
return enumItem.GetAttributeValue( typeof (RussianName), string .Empty);
}
}
}
Source: https://habr.com/ru/post/68253/
All Articles