property 与 attribute 的区别?
2024-09-24 13:00:16
一个是属性,用于存取类的字段,一个是特性,用来标识类,方法等的附加性质。
属性:
class TimePeriod
{
private double seconds; public double Hours
{
get { return seconds / ; }
set { seconds = value * ; }
}
} class Program
{
static void Main()
{
TimePeriod t = new TimePeriod(); // Assigning the Hours property causes the 'set' accessor to be called.
t.Hours = ; // Evaluating the Hours property causes the 'get' accessor to be called.
System.Console.WriteLine("Time in hours: " + t.Hours);
}
}
// Output: Time in hours: 24
特性:
using System;
using System.Reflection; namespace CustomAttrCS
{
// An enumeration of animals. Start at 1 (0 = uninitialized).
public enum Animal
{
// Pets.
Dog = ,
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.
*/
最新文章
- ASP.NET MVC企业级实战目录
- C++中new,delete和new[] ,delete[]的分析
- Android Service小记
- JQuery学习笔记---jquery对象和DOM对象的关系
- Opencv SkinOtsu皮肤检测
- 从QQ网站中提取的纯JS省市区三级联动
- Hadoop集群基准测试
- 导出cluster log
- AForge.NET 工具源码下载
- ios给textView提价提示性文字
- jdk8的新特性 Lambda表达式
- JAVA虚拟机系列文章
- B. Order Book(Codeforces Round #317 )
- 用ASP.NET Core 2.0 建立规范的 REST API
- java里常用的redis客户端简介
- struts2+springmvc+hibernate开发。个人纪录
- 缓存系列之四:redis持久化与redis主从复制
- element 表格元素 超链接
- python3.4学习笔记(三) idle 清屏扩展插件
- 知识点查缺补漏贴02:Linux环境fork()函数详解
热门文章
- 20172333 2017-2018-2 《Java程序设计》第3周学习总结
- [转]Java常用概念解答
- CDOJ 1280 772002画马尾 每周一题 div1 矩阵快速幂 中二版
- Xcode8 报 ”xx“is missing from working copy 的问题解决方法
- sqlserver 脚本 多条记录遍历
- segmentfault hackthon比赛感悟
- 对自助提卡系统EDLM的一次代码审计
- hdu 4893Wow! Such Sequence!
- php 中 拓展 xdebug的完全理解
- RocketMQ通信协议