property 与 attribute 的区别?
2013-04-16 11:48
393 查看
一个是属性,用于存取类的字段,一个是特性,用来标识类,方法等的附加性质。
属性:
View Code
属性:
View Code
using System; using System.Reflection; namespace CustomAttrCS { // An enumeration of animals. Start at 1 (0 = uninitialized). public enum Animal { // 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)] public void DogMethod() { } [AnimalType(Animal.Cat)] public void CatMethod() { } [AnimalType(Animal.Bird)] public void 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. */
相关文章推荐
- javascript中attribute和property的区别详解
- 理解特性attribute 和 属性property的区别 及相关DOM操作总结
- JS中Attribute 和 property的区别
- JavaScript中property和attribute的区别详细介绍
- Property和attribute的区别
- Attribute和Property的区别
- HTML中的attribute属性和JavaScript中的property属性的详解以及区别
- javascript中attribute和property的区别详解
- C#中 property 与 attribute的区别,他们各有什么用处,这种机制的好处在哪里?
- DOM中Property与Attribute的区别
- 转 区别C#中的两个属性(Property和Attribute)
- 【心得】Attribute和Property的区别;
- property和attribute2种表示属性的区别
- prop(Property)和attr(attribute)用法区别
- DOM 中 Property 和 Attribute 的区别
- property和attribute的区别
- property 与 attribute的区别
- Attribute与Property的区别
- property和attribute的区别
- property和attribute的区别