以下我学习特性的例子。结果和我想你的不一样。不知为什么??
using System;
using System.Reflection; 
//应用反射技术获得特性信息
namespace AttributeTest

{
[AttributeUsageAttribute(AttributeTargets.All, //可应用任何元素
AllowMultiple = true, //允许应用多次
Inherited = false)] //不继承到派生类
public class MyselfAttribute : System.Attribute
{
//定义字段
private string _name;
private int _age;
private string _memo;
public MyselfAttribute(string name, int age)
{
_name = name;
_age = age;
}
public string Name
{
get
{ return _name == null ? string.Empty : _name; }
}
public int Age
{
get
{ return _age; }
}
public string Memo
{
get
{ return _memo; }
set
{ _memo = value; }
}
//定义方法
public void ShowName()
{
Console.WriteLine("Hello, ", _name == null ? "world." : _name);
}
}
[Myself("无声E梦", 25, Memo = "我是一个程序员")]
public class Mytest
{
public static void Main(string[] args)
{
Type tp = typeof(Mytest);
MyselfAttribute myAttribute = (MyselfAttribute)Attribute.GetCustomAttribute(tp,typeof(MyselfAttribute));
if(myAttribute != null)
{
Console.WriteLine("Name:",myAttribute.Name);
Console.WriteLine("Age: ", myAttribute.Age);
Console.WriteLine("Memo: ", myAttribute.Name, myAttribute.Memo);
}
}
}
}
结果为: