Attribute یا همان صفات دقیقا چرا اهمیت دارند و کاربرد آنها دقیقا چیست
سلام..
من دقیقا اهمیت 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();
}
}
}
من میگم باید ارور بده اما هیچ اتفاقی نمیفته..
نقل قول: Attribute یا همان صفات دقیقا چرا اهمیت دارند و کاربرد آنها دقیقا چیست
آقا خواهشا یکی از دوستان یه جوابی به من بدهند.
نقل قول: Attribute یا همان صفات دقیقا چرا اهمیت دارند و کاربرد آنها دقیقا چیست
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();
}
}