PropertyInfo Class
Represents a property of a class or interface. This class inherits from MemberInfo
.
Summary
Members | Description |
---|---|
Properties | Provides access to the properties of the current property. |
Methods | Provides access to the methods of the current property. |
Events | Provides access to the events of the current property. |
Attributes | Provides access to the attributes of the current property. |
Inheritance
Object
MemberInfo
PropertyInfo
Remarks
The PropertyInfo
class is used to inspect properties of a type at runtime. It allows you to retrieve information about a property such as its name, type, accessibility, and whether it is static or instance. You can also use PropertyInfo
to get and set the value of a property on an object.
Methods
Public Methods
Name | Description |
---|---|
GetValue(Object obj, Object[] index) |
Gets the value of the property on a specified object. |
SetValue(Object obj, Object value, Object[] index) |
Sets the value of the property on a specified object. |
GetAccessors(Boolean nonPublic) |
Returns an array of MethodInfo objects representing the public accessors (get and set) of the property. |
CanRead |
Gets a value indicating whether the property can be read. |
CanWrite |
Gets a value indicating whether the property can be written. |
PropertyType |
Gets the type of the property. |
Name |
Gets the name of the property. |
GetCustomAttributes(Type attributeType, Boolean inherit) |
Gets a custom attribute of a specified type that is applied to this member and, optionally, searches up the hierarchy chain for inherited attributes. |
Properties
Public Properties
Name | Description |
---|---|
DeclaringType |
Gets the class that declares this member. |
IsSpecialName |
Gets a value indicating whether the name of this member is special. |
MemberType |
Gets the type of this member. |
Name |
Gets the name of the current member. |
ReflectedType |
Gets the type that was queried to get this member. |
Example
using System;
using System.Reflection;
public class ExampleClass
{
public string MyProperty { get; set; }
private int _myPrivateField;
public int MyOtherProperty
{
get { return _myPrivateField; }
set { _myPrivateField = value; }
}
}
public class Program
{
public static void Main(string[] args)
{
Type myType = typeof(ExampleClass);
// Get all public properties
PropertyInfo[] properties = myType.GetProperties();
foreach (PropertyInfo prop in properties)
{
Console.WriteLine($"Property Name: {prop.Name}");
Console.WriteLine($"Property Type: {prop.PropertyType.Name}");
Console.WriteLine($"Can Read: {prop.CanRead}");
Console.WriteLine($"Can Write: {prop.CanWrite}");
// Example of getting and setting a property value
if (prop.Name == "MyProperty")
{
ExampleClass instance = new ExampleClass();
prop.SetValue(instance, "Hello Reflection!");
object value = prop.GetValue(instance);
Console.WriteLine($"Value of {prop.Name}: {value}");
}
Console.WriteLine("---");
}
}
}