在C#中,可以使用PropertyInfo類實現(xiàn)深層屬性訪問。首先,獲取對象的類型信息,然后使用GetProperty方法獲取指定屬性的PropertyInfo對象,再遞歸地獲取嵌套屬性的PropertyInfo對象,直到達到需要訪問的深層屬性。
以下是一個示例代碼,演示如何使用PropertyInfo實現(xiàn)深層屬性訪問:
using System;
using System.Reflection;
public class Person
{
public string Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string Street { get; set; }
public string City { get; set; }
}
class Program
{
static void Main()
{
Person person = new Person
{
Name = "John Doe",
Address = new Address
{
Street = "123 Main St",
City = "City"
}
};
PropertyInfo propertyInfo = GetDeepPropertyInfo(person, "Address.City");
if (propertyInfo != null)
{
object propertyValue = GetDeepPropertyValue(person, "Address.City");
Console.WriteLine(propertyInfo.Name + ": " + propertyValue);
}
}
static PropertyInfo GetDeepPropertyInfo(object obj, string propertyName)
{
Type type = obj.GetType();
string[] propertyNames = propertyName.Split('.');
PropertyInfo propertyInfo = null;
foreach (string name in propertyNames)
{
propertyInfo = type.GetProperty(name);
if (propertyInfo != null)
{
type = propertyInfo.PropertyType;
}
else
{
return null;
}
}
return propertyInfo;
}
static object GetDeepPropertyValue(object obj, string propertyName)
{
Type type = obj.GetType();
string[] propertyNames = propertyName.Split('.');
object propertyValue = null;
foreach (string name in propertyNames)
{
PropertyInfo propertyInfo = type.GetProperty(name);
if (propertyInfo != null)
{
propertyValue = propertyInfo.GetValue(obj);
obj = propertyValue;
type = propertyInfo.PropertyType;
}
else
{
return null;
}
}
return propertyValue;
}
}
在上面的示例中,GetDeepPropertyInfo和GetDeepPropertyValue方法分別用于獲取深層屬性的PropertyInfo對象和屬性值。通過使用這兩個方法,可以實現(xiàn)對任意深層屬性的訪問。