Attributes یا صفات درواقع توصیف کننده یه type , method , property ... هستند ... صفات یه چیزی مثل comment هستند با این تفاوت که runtime و با کد قابل دسترسی هستند ...
Attributes
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Struct,
AllowMultiple = false, Inherited = true)]
public class MyAttribute : Attribute
{
private string regKey = "a12nf";
private string pRegKey;
public MyAttribute(string regKey)
{
pRegKey = regKey;
}
public string Validate()
{
if (this.regKey == pRegKey)
return ("Permitted to use this App");
else
return ("Not registered to use this App");
}
}
class Program
{
[MyAttribute("hello")]
public static string SayHello(string str)
{
return str;
}
static void Main()
{
System.Reflection.MethodInfo[] methods = typeof(Program).GetMethods();
foreach (System.Reflection.MethodInfo method in methods)
{
MyAttribute att = Attribute.GetCustomAttribute(method,typeof(MyAttri bute), false) as MyAttribute;
if (att == null)
continue;
Console.WriteLine(method.Name + " " + att.Validate() + " " + att.GetType());
}
Console.ReadLine();
}
}