读书人

用特性如何标记属性

发布时间: 2013-11-08 17:52:14 作者: rapoo

用特性怎么标记属性
我想用特性标记属性,这个属性的特性等于某个值时执行一个操作,求用法
[解决办法]
做法感觉挺奇葩,感兴趣我写了一下,没写完下班了,你可以自己改一下


class TestAttributes
{
private string test;

[MyAttribute(My="变量信息")]
public string Test
{
get { return test; }
set { test = value; }
}
}

[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
private string my;
/// <summary>
/// 实体实际对应的表名
/// </summary>
public string My
{
get { return my; }
set { my = value; }
}
}

调用代码,目前只写到遍历特性名称,肚子饿了,啃饭去,明天有空的话再接着写

Type tAb = typeof(TestAttributes);
foreach (System.Reflection.PropertyInfo propInfo in tAb.GetProperties())
{
MessageBox.Show(propInfo.Name);
object[] testAb = propInfo.GetCustomAttributes(typeof(MyAttribute), true);
foreach (object cAb in testAb)
{
MessageBox.Show(cAb.ToString());
}
}

读书人网 >C#

热点推荐