PDA

View Full Version : نحوه نوشتن Attributes



manager
دوشنبه 04 اردیبهشت 1385, 05:34 صبح
سلام

می خواستم اگر مقدور هست یه چند تا رفرنس (ترجیها فارسی ) در مورد نوشتن Attribute ها معرفی کنید...:خجالت:

از دوستان اگر کسی یه توضیح کوچیک هم در مورد اینکه Attributeها کی اجرا می شن و برای چی نوشته می شن (در چه جاهائی باید به کار برده شوند) و اینکه داخل خودشون چه امکاناتی دارند توضیح بدن دیگه عالی می شه !!!!!!!!!:تشویق:

omid_Ahmadi
دوشنبه 04 اردیبهشت 1385, 07:24 صبح
اتربیوتها هم در واقع یه سری کلاس هستن که فقط از کلاس Attribute مشتق شدن، به همین دلیل می تونن به همون صورتی که میبینی استفاده بشن. معمولا کمتر پیش میاد که توی یه برنامه بخوای خودت یه اتربیوت بنویسی.
در هر صورت این کد یه مثال برای نوشتن اتربیوت و استفاده از اونه:


using System;
using System.Reflection;

namespace CustomAttrCS
{
// An enumeration of animals. Start at 1 (0 = uninitialized).
public
enumAnimal
{
// Pets.
Dog
= 1,
Cat
,
Bird
,
}
// A custom attribute to allow a target to have a pet.
public class AnimalTypeAttribute : Attribute
{
// The constructor is called when the attribute is set.
public AnimalTypeAttribute(Animal pet)
{
thePet = pet;
}

// Keep a variable internally ...
protected Animal thePet;
// .. and show a copy to the outside world.
public Animal Pet
{
get { return thePet; }
set { thePet = Pet; }
}
}

// A test class where each method has its own pet.
class AnimalTypeTestClass
{
[AnimalType(Animal.Dog)]
publicvoid DogMethod()
{
}

[AnimalType(Animal.Cat)]
publicvoid CatMethod()
{
}

[AnimalType(Animal.Bird)]
publicvoid BirdMethod()
{
}
}

class DemoClass
{
static void Main(string[] args)
{
AnimalTypeTestClass testClass = new AnimalTypeTestClass();
Type type = testClass.GetType();
// Iterate through all the methods of the class.
foreach (MethodInfo mInfo in type.GetMethods())
{
// Iterate through all the Attributes for each method.
foreach (Attribute attr in
Attribute.GetCustomAttributes(mInfo))
{
// Check for the AnimalType attribute.
if (attr.GetType() == typeof (AnimalTypeAttribute))
Console.WriteLine(
"Method {0} has a pet {1} attribute.",
mInfo.Name, ((AnimalTypeAttribute) attr).Pet);
}
}
}
}
}

/*
* Output:
* Method DogMethod has a pet Dog attribute.
* Method CatMethod has a pet Cat attribute.
* Method BirdMethod has a pet Bird attribute.
*/

خواستی لینک زیر رو ببین، در این مورد توضیح داده:
http://msdn2.microsoft.com/en-US/library/system.attribute(VS.80).aspx

manager
دوشنبه 04 اردیبهشت 1385, 22:41 عصر
دست شما درد نکنه آقای احمدی..
می شه توضیح بدین فقط چه زمانی Attribute اجرا می شه ؟ و چه قابلیت هائی ممکنه بتونه برای متد ها یا کلاس های فراهم بکنه ؟

mohssen91
سه شنبه 14 اردیبهشت 1395, 12:19 عصر
سلام دوستان

من هرچی راجع به attribute ها جستجو میکنم هر جا یه جوری توضیح میدن و من اصلا گیج شدم

فرق بین اون چیز هایی که توی [ ] نوشته میشن با اون چیزهایی که توی < > نوشته میشن چیه ؟

آیا هر دو اینها attribute هستن ؟

و اینکه آیا تعریف attribute ها برای property فرق داره با attribute های method

آیا لیستی هست که تمام attribute ها رو در دسترس قرار بده

خیلی خیلی ممنونم