Type.GetProperty 方法
Get the current Type -specific attributes.
parameter
- name
- String
String containing the name of the property to be acquired.
- bindingAttr
- BindingFlags
Bitwise combination of enumeration values, these values specify how to search.
Or if it is the Default , then return null
.
return
Represent objects that meet the specified requirements of the property (if found); otherwise null
.
Examples
The following example retrieves the type of user-defined classes, the class attribute to retrieve and display according to the specified attribute name binding constraints.
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); } } }
Need PropertyInfo.SetValue method
The method of setting the value of the specified attribute to modify the properties of the object visibility
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;
abnormal
index
Array does not contain the parameter type.
Or can not find the property's set
value function.
Or value
can not be converted PropertyType type.
The object does not match the target type, it is an example of a property or properties, but obj
is null
.
index
It does not match the number of parameters in the number of parameters used in the index attribute.
Attempt to gain unauthorized access classes in private or protected method.
Error setting property value. For example, an index for the specified attribute index value is out of range. InnerException property indicates the cause of the error.