PropertyInfo 。属性属性
このプロパティは、メンバーに関連付けられた特性です。 すべてのメンバーは、特定のメンバー型定義の機能セットに関して持っています。 プロパティは、ユーザーがこのプロパティは、デフォルトのプロパティであるかどうかを知ることができる機能SpecialNameのようにプロパティと。
取得するには、属性のプロパティを、最初のクラス型を取得します。 タイプから得られPropertyInfo。 PropertyInfo特性を獲得しました。
公式例:取得属性クラス
1 using System;
2 using System.Reflection;
3
4 public class Myproperty
5 {
6 private string caption = "Default caption";
7 public string Caption
8 {
9 get{return caption;}
10 set {if(caption!=value) {caption = value;}
11 }
12 }
13 }
14
15 class Mypropertyinfo
16 {
17 public static int Main(string[] args)
18 {
19 Console.WriteLine("\nReflection.PropertyInfo");
20
21 // Define a property.
22 Myproperty Myproperty = new Myproperty();
23 Console.Write("\nMyproperty.Caption = " + Myproperty.Caption);
24
25 // Get the type and PropertyInfo.
26 Type MyType = Type.GetType("Myproperty");
27 PropertyInfo Mypropertyinfo = MyType.GetProperty("Caption");
28
29 // Get and display the attributes property.
30 PropertyAttributes Myattributes = Mypropertyinfo.Attributes;
31
32 Console.Write("\nPropertyAttributes - " + Myattributes.ToString());
33
34 return 0;
35 }
36 }
公式リファレンス:http://msdn.microsoft.com/zh-cn/library/system.reflection.propertyinfo.attributes
例:注意:フィールドに無効であるように見えます
クラスのユーザーを構築する最初の
1 namespace ClassLibrary1
2 {
3 public class User
4 {
5 private int userid = 1;
6 public int Userid
7 {
8 get { return userid; }
9 set { userid = value; }
10 }
11 private string userName = "jghg";
12 public string UserName{
13 get { return userName; }
14 set { userName = value; }
15 }
16 private string address = "ghjghj";
17 public string Address{
18 get { return address; }
19 set { address = value; }
20 }
21 private string email = "jhgjhg";
22 public string Email{
23 get { return email; }
24 set { email = value; }
25 }
26 private string phone = "ghjgjg";
27 public string Phone
28 {
29 get { return phone; }
30 set { phone = value; }
31 }
32 }
33 }
その後、メインプログラムで属性クラスを取得し、コードを見て
1 namespace ConsoleApplication2 {
2 class Program {
3 static void Main(string[] args)
4 {
5 Type type = typeof(ClassLibrary1.User);
6 object obj = Activator.CreateInstance(type);
7 PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
8 foreach (PropertyInfo p in props) {
9 Console.WriteLine(p.Name);
10 }
11 Console.ReadLine();
12 }
13 }
14 }
私たちは、名前空間を導入する必要があります。
するSystem.Reflectionを使用しました。
ます。https://my.oschina.net/weisenz/blog/200614で再現