C#遍历类的属性 PropertyInfo.Attributes(转)
PropertyInfo.Attributes 属性
此属性表示与成员关联的特性。 所有成员都具有相对于特定成员类型定义的特性集。 属性特性使用户能够知道此属性是否是默认属性、SpecialName 属性等等。
若要获取 Attributes 属性,请先获取类类型。 从 Type 获取 PropertyInfo。 从 PropertyInfo 获取特性。
官方示例:获取类的特性
using System; using System.Reflection; public class Myproperty { private string caption = "Default caption"; public string Caption { get{return caption;} set {if(caption!=value) {caption = value;} } } } class Mypropertyinfo { public static int Main(string[] args) { Console.WriteLine("\nReflection.PropertyInfo"); // Define a property. Myproperty Myproperty = new Myproperty(); Console.Write("\nMyproperty.Caption = " + Myproperty.Caption); // Get the type and PropertyInfo. Type MyType = Type.GetType("Myproperty"); PropertyInfo Mypropertyinfo = MyType.GetProperty("Caption"); // Get and display the attributes property. PropertyAttributes Myattributes = Mypropertyinfo.Attributes; Console.Write("\nPropertyAttributes - " + Myattributes.ToString()); return 0; } }
官方参考:http://msdn.microsoft.com/zh-cn/library/system.reflection.propertyinfo.attributes
一个例子: 注意:貌似对字段无效
先建一个类User
namespace ClassLibrary1 { public class User { private int userid = 1; public int Userid { get { return userid; } set { userid = value; } } private string userName = "jghg"; public string UserName{ get { return userName; } set { userName = value; } } private string address = "ghjghj"; public string Address{ get { return address; } set { address = value; } } private string email = "jhgjhg"; public string Email{ get { return email; } set { email = value; } } private string phone = "ghjgjg"; public string Phone { get { return phone; } set { phone = value; } } } }
接着在主程序中获取类的属性,看代码
namespace ConsoleApplication2 { class Program { static void Main(string[] args) { Type type = typeof(ClassLibrary1.User); object obj = Activator.CreateInstance(type); PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo p in props) { Console.WriteLine(p.Name); } Console.ReadLine(); } } }
需要引入命名空间:
using System.Reflection;
链接:http://www.cnblogs.com/weisenz/archive/2012/04/20/2458658.html

浙公网安备 33010602011771号