Type.GetProperty 方法
获取当前 Type 的特定属性.
参数
name
String
包含要获取的属性名的字符串.
- bindingAttr
- BindingFlags
枚举值的按位组合, 这些值指定如何进行搜索.
或 若为 Default, 则返回 null.
返回
PropertyInfo
表示符合指定需求的属性的对象 (如果找到的话); 否则为 null.
示例
下面的示例检索用户定义的类的类型, 检索该类的属性, 并根据指定的绑定约束显示属性名称.
- using System;
- using System.Reflection;
- class MyClass
- {
- private int myProperty;
- // Declare MyProperty.
- public int MyProperty
- {
- get
- {
- return myProperty;
- }
- set
- {
- myProperty=value;
- }
- }
- }
- public class MyTypeClass
- {
- public static void Main(string[] args)
- {
- try
- {
- // Get Type object of MyClass.
- Type myType=typeof(MyClass);
- // Get the PropertyInfo by passing the property name and specifying the BindingFlags.
- PropertyInfo myPropInfo = myType.GetProperty("MyProperty", BindingFlags.Public | BindingFlags.Instance);
- // Display Name propety to console.
- Console.WriteLine("{0} is a property of MyClass.", myPropInfo.Name);
- }
- catch(NullReferenceException e)
- {
- Console.WriteLine("MyProperty does not exist in MyClass." +e.Message);
- }
- }
- }
需要用 PropertyInfo.SetValue 方法
设置指定对象的属性值方法来修改属性的可见性
- NameValueCollection paramsCollection = context.Request.Form;
- var propInfo = paramsCollection.GetType().GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
- propInfo.SetValue(paramsCollection, false, new object[] { });
- System.Collections.Specialized.NameObjectCollectionBase.KeysCollection keys = paramsCollection.Keys;
- SetValue(Object, Object, BindingFlags, Binder, Object[], CultureInfo)
异常
ArgumentException
index 数组不包含所需的参数类型.
或 找不到该属性的 set 取值函数.
或 value 无法转换为 PropertyType 的类型.
TargetException
该对象与目标类型不匹配, 或者某属性是实例属性但 obj 为 null.
TargetParameterCountException
index 中的参数数量与索引属性采用的参数数量不匹配.
MethodAccessException
试图非法访问类中的私有或受保护方法.
TargetInvocationException
设置属性值时出错. 例如, 为一个索引属性指定的索引值超出范围. InnerException 属性指示出错的原因.
来源: http://www.bubuko.com/infodetail-3354775.html