简单的例子。
自定义Attribute

自定义Attribute
1
using System;
2
3
namespace Relaction.test1
4

{
5
/**//// <summary>
6
/// 自定义的Attribute类型。
7
/// </summary>
8
///
9
[AttributeUsage(AttributeTargets.Class,Inherited=false,AllowMultiple=false)]
10
public class ClassShowProcessAttribute:Attribute
11
{
12
private bool _show = false;
13
public bool Show
14
{
15
get
16
{
17
return _show;
18
}
19
}
20
public ClassShowProcessAttribute(bool show)
21
{
22
_show = show;
23
}
24
}
25
}
使用上面的Attribute。

使用Attribute
1
using System;
2
3
namespace Relaction.test1
4

{
5
/**//// <summary>
6
/// 给这个类贴上自定义的属性。
7
/// </summary>
8
///
9
[ClassShowProcess(false)]
10
public class AttrClassTest
11
{
12
public AttrClassTest()
13
{}
14
}
15
}
16
应用测试:

应用测试
1
private void button2_Click(object sender, System.EventArgs e)
2
{
3
object[] o = new object[]
{new AttrClassTest(),new AttrClassTest(),"TEST"};
4
foreach(object item in o)
5
{
6
ClassShowProcessAttribute[] attr = (ClassShowProcessAttribute[])item.GetType().GetCustomAttributes(typeof(ClassShowProcessAttribute),false);
7
if(attr.Length != 0)
8
{
9
if(attr[0].Show)
10
{
11
label1.Text += item.ToString();
12
}
13
}
14
}
15
}
1
using System;2

3
namespace Relaction.test14


{5

/**//// <summary>6
/// 自定义的Attribute类型。7
/// </summary>8
/// 9
[AttributeUsage(AttributeTargets.Class,Inherited=false,AllowMultiple=false)]10
public class ClassShowProcessAttribute:Attribute11

{12
private bool _show = false;13
public bool Show14

{15
get16

{17
return _show;18
}19
}20
public ClassShowProcessAttribute(bool show)21

{22
_show = show;23
}24
}25
}1
using System;2

3
namespace Relaction.test14


{5

/**//// <summary>6
/// 给这个类贴上自定义的属性。7
/// </summary>8
/// 9
[ClassShowProcess(false)]10
public class AttrClassTest11

{12
public AttrClassTest()13

{}14
}15
}16

1
private void button2_Click(object sender, System.EventArgs e)2

{3

object[] o = new object[]
{new AttrClassTest(),new AttrClassTest(),"TEST"};4
foreach(object item in o)5

{6
ClassShowProcessAttribute[] attr = (ClassShowProcessAttribute[])item.GetType().GetCustomAttributes(typeof(ClassShowProcessAttribute),false);7
if(attr.Length != 0)8

{9
if(attr[0].Show)10

{11
label1.Text += item.ToString();12
}13
}14
}15
}

浙公网安备 33010602011771号