反射:将每个属性转换为List<T>

3

我正在尝试使用反射来遍历对象的属性,并将每个属性转换为List<T>

class MyObj
{
    public List<A> As { get; set; }
    public List<B> Bs { get; set; }
    public List<C> Cs { get; set; }
    public List<D> Ds { get; set; }
    public List<E> Es { get; set; }
}

我有一个方法,它接受一个对象,我正在尝试将每个属性的值转换为 List<T>,但是它没有起作用。

void ProcessObject(object o)
{
    foreach (PropertyInfo propertyInfo in this.GetType().GetProperties())
    {
        Type propertyType = propertyInfo.PropertyType;
        Type propertyListType;

        if (TryListOfWhat(propertyType, out propertyListType))
        {
            var propertyValue = (List<propertyListType>)propertyInfo.GetValue(this);
        }
    }
}

public static bool TryListOfWhat(Type type, out Type innerType)
{
    Contract.Requires(type != null);

    var interfaceTest = new Func<Type, Type>(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>) ? i.GetGenericArguments().Single() : null);

    innerType = interfaceTest(type);
    if (innerType != null)
    {
        return true;
    }

    foreach (var i in type.GetInterfaces())
    {
        innerType = interfaceTest(i);
        if (innerType != null)
        {
            return true;
        }
    }

    return false;
}

现在我知道属性是一个 List<T>,并且我有 T 的类型,那么我该如何将属性对象值强制转换为 List<T>

我创建了另一个问题来解释我实际想要做的事情:https://stackoverflow.com/questions/22975430/serialize-deserialize-inmemorydatabase


4
在编译时无法将对象转换为未知类型。您应该发布您正在尝试做什么,以便我们可以理解。 - Gabe
据我所知,这是不可能的。你只能将它们转换为IList而不是List<T> - Selman Genç
如果你正在使用反射并且不知道实际涉及的类型,那么你只有两个朋友:object和dynamic。最多你可以使用dynamic,但仅限于此。 - MikeSW
1个回答

0
你可以尝试使用 "dynamic" 代替 "var",并将属性保留为对象,这样就可以像以前一样调用 List 成员而不进行编译时检查。

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