动态获取值并将其转换为 PropertyInfo.PropertyType 类型的对象

3
我的问题是:如何制作

标签?
PropertyInfo.GetValue(object, null);

返回值应转换为PropertyType,而不是返回对象。

我尝试了Convert.ChangeType但没有成功。

谢谢。

更新1:

更多细节:

我的代码:

foreach (var propertyInfo in customerInfo.CustomerRelationship.GetType().GetProperties())
{
    var relationshipList = (IList)propertyInfo.GetValue(customerInfo.CustomerRelationship, null);
    foreach (var relationship in relationshipList)
    {
    }
}

使用

public struct CustomerInfo
{
    public Customer CustomerItem { get; set; }
    public Relationship CustomerRelationship { get; set; }
}

public class Relationship
{
    public List<Contact> ContactItems { get; set; }
    public List<Department> DepartmentItems { get; set; }
    ..........
}

由于无法动态转换每个关系项的显示,因此无法进行比较、查询(Linq)和数据库操作。


GetValue 已经会返回正确类型的 。你想做什么? - Thom Smith
是的,类型正确,但类型是对象而不是确切的类。 - Xuân An
我不明白你想要实现什么。 - Thom Smith
1个回答

3

你无法这样做。

为了简单起见,可以编写一个通用的包装器。

public static T GetValue<T>(Object obj1, Object obj2)
{
return (T)PropertyInfo.GetValue(obj1, obj2);
}

为了安全起见,您可能希望将GetValue的结果存储在本地变量中,并检查它是否真的是类型T,以确保(尽可能)转换不会抛出异常。 - Tim Copenhaver
由于T可能是值类型,因此as不一定有效。您仍然可以使用is,如果is返回true,则执行常规转换。 - Tim Copenhaver

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接