using System;
using System.Reflection;
// 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 = value; }
}
}// 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() { }
}
namespace ConsoleApplication3
{
class Program
{
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);
}
}
}
}
}
C# 特性demo
原创
©著作权归作者所有:来自51CTO博客作者RandTsui的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:C# DateTime和时间戳
下一篇:js 移动端 指尖摩擦小游戏源码
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
c# 特性实践
1 ...
特性 技术