property 与 attribute 的区别?
2015-10-21 21:16
429 查看
一个是属性,用于存取类的字段,一个是特性,用来标识类,方法等的附加性质。
属性:
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. */
View Code
相关文章推荐
- Linux下OpenSSL 安装详解 +图解
- shell 统计出上个月中旬到本月中旬的所有工作日
- Linux 操作系统配置——总体架构目录
- iOS开发之 MVVM的架构设计与团队协作的重要性
- OpenCV-Mat结构详解
- linux学习笔记--centos 安装
- 自己写的第一本Linux教程,也小小的班门弄斧一下
- Linux配置网卡
- [笔记] Convex Optimization 2015.10.14
- [笔记] Convex Optimization 2015.09.30
- windows下开发的Web Projectj项目放到Linux服务器下出现路径问题
- linux驱动开发
- Centos6.5 下 Maven 安装
- shell jsonj解析
- Apache-You don't have permission to access / on this server. Apache, win 7
- 【学习总结】【多线程】 多线程概要 & GDC & NSOperation
- 鸟哥的Linux私房菜-学习笔记-第一章【Linux】
- PeopleSoft Home Subdirectories
- People Tools catalog tables.
- 鸟哥的Linux私房菜-学习笔记-概论