PDA

View Full Version : Attribute یا همان صفات دقیقا چرا اهمیت دارند و کاربرد آنها دقیقا چیست



amirjalili
چهارشنبه 11 اسفند 1389, 13:19 عصر
سلام..
من دقیقا اهمیت attribute ها رو نفهمیدم..
همه جا میگن موقع کامپایل پیغام یا خطا میده و در واقع اطلاعات توضیحی برای متد ها و کلاس ها است ..

به نظر شما در این کد زیر چه اتفاقی باید با توجه به تعریف Attribute بیافته؟


using System;
namespace RegKeyAttributeTestor
{
[AttributeUsage(AttributeTargets.Method|AttributeTa rgets.Struct,
AllowMultiple=false,Inherited=true)]
public class MyAttribute:Attribute
{
private string regKey="a12nf";
public MyAttribute(string regKey)
{
if(this.regKey==regKey)
{
Console.WriteLine("Permitted to use this App");
}
else
{
Console.WriteLine("Not registered to use this App");
}
}
}
//End Attribute class code
class useAttrib
{
[MyAttribute("hello")]
public static string SayHello(string str)
{
return str;
}
static void Main()
{
Console.WriteLine(SayHello("Hello to Sufyan"));
Console.ReadLine();
}
}

}


من میگم باید ارور بده اما هیچ اتفاقی نمیفته..

amirjalili
پنج شنبه 12 اسفند 1389, 08:37 صبح
آقا خواهشا یکی از دوستان یه جوابی به من بدهند.

exlord
پنج شنبه 12 اسفند 1389, 12:01 عصر
Attributes یا صفات درواقع توصیف کننده یه type , method , property ... هستند ... صفات یه چیزی مثل comment هستند با این تفاوت که runtime و با کد قابل دسترسی هستند ...
Attributes (http://msdn.microsoft.com/en-us/library/z919e8tw(v=vs.80).aspx)

[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();
}
}