你SubProperty
成员实际上是一个Field
而不是Property
,那就是为什么你不能通过使用GetProperty(string)
方法来访问它。在当前的情况下,您应该先使用以下类来获取SubProperty
字段,然后再获取Address
属性。
该课程将允许您通过使用适当类型关闭类型T
来指定您的财产的返回类型。然后,您只需将第一个参数对象添加到您正在提取的成员中。第二个参数是您正在提取的字段的名称,而第三个参数是您尝试获取其值的属性的名称。
class SubMember<T>
{
public T Value { get; set; }
public SubMember(object source, string field, string property)
{
var fieldValue = source.GetType()
.GetField(field)
.GetValue(source);
Value = (T)fieldValue.GetType()
.GetProperty(property)
.GetValue(fieldValue, null);
}
}
为了在您的上下文中获得所需的值,只需执行以下几行代码即可。
class Program
{
static void Main()
{
var t1 = new TestClass1();
Console.WriteLine(new SubMember<string>(t1, "SubProperty", "Address").Value);
}
}
这会给你包含在Address
属性中的值。只要确保你首先为该属性添加一个值。
但是,如果您确实想将班级的字段更改为属性,则应对原始SubMember
类进行以下更改。
class SubMemberModified<T>
{
public T Value { get; set; }
public SubMemberModified(object source, string property1, string property2)
{
var propertyValue = source.GetType()
.GetProperty(property1)
.GetValue(source, null);
Value = (T)propertyValue.GetType()
.GetProperty(property2)
.GetValue(propertyValue, null);
}
}
这个班的学生将允许您从您最初的类中提取属性,并从第二个属性,这是从第一特性提取的值。