@manhng

Welcome to my blog!

Custom Attributes

August 23, 2021 17:48

Custom Attributes (edit)

Tutorial: Use attributes - C# | Microsoft Docs

Writing Custom Attributes | Microsoft Docs

 public static object GetPropValue(object src, string propName)
 {
     return src.GetType().GetProperty(propName).GetValue(src, null);
 }
DateTime now = DateTime.Now;
int min = GetPropValue<int>(now, "TimeOfDay.Minutes");
int hrs = now.GetPropValue<int>("TimeOfDay.Hours");
namespace ConsoleApp1
{
public class Book
{
[Author("AuthorName")]
public string Name
{
get; private set;
}
}

[AttributeUsage(AttributeTargets.Class | AttributeTargets.GenericParameter | AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property)]
public class AuthorAttribute : Attribute
{
public AuthorAttribute(string name)
{
this._Name = name;
}

private string _Name;

public string Name
{
get { return this._Name; }
set { this._Name = value; }
}
}

class Program
{
private static void Main(string[] args)
{
GetAuthors();

Environment.Exit(-1);
}

private static Dictionary<string, string> GetAuthors()
{
Dictionary<string, string> _dict = new Dictionary<string, string>();

PropertyInfo[] props = typeof(Book).GetProperties();
foreach (PropertyInfo prop in props)
{
object[] attrs = prop.GetCustomAttributes(true);
foreach (object attr in attrs)
{
AuthorAttribute authAttr = attr as AuthorAttribute;
if (authAttr != null)
{
string propName = prop.Name;
string auth = authAttr.Name;

_dict.Add(propName, auth);
}
}
}

return _dict;
}
}
}

Categories

Recent posts