C#修改属性的访问性

Type.GetProperty 方法

获取当前 Type 的特定属性。

参数

name
String

包含要获取的属性名的字符串。

bindingAttr
BindingFlags

枚举值的按位组合,这些值指定如何进行搜索。

若为 Default,则返回 null

返回

表示符合指定需求的属性的对象(如果找到的话);否则为 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;

异常

index 数组不包含所需的参数类型。

找不到该属性的 set 取值函数。

value 无法转换为 PropertyType 的类型。

该对象与目标类型不匹配,或者某属性是实例属性但 objnull

index 中的参数数量与索引属性采用的参数数量不匹配。

试图非法访问类中的私有或受保护方法。

设置属性值时出错。 例如,为一个索引属性指定的索引值超出范围。 InnerException 属性指示出错的原因。

猜你喜欢

转载自www.cnblogs.com/Tpf386/p/12112681.html