使用 T 的 属性 创建具有 属性 值的 属性 类型的新对象?

Using a property of T to create a new object of the property type with the property values?

我需要一种方法将类型 T 的对象的属性转换为 属性 类型的对象,以及它们在 T 中的值。我这样做的原因是我可以检查是否属性 是或继承自 IEnumerable(列表、数组等),如果是,那么我需要将该 IEnumerable 作为要处理的对象传递。 所以目前我有

foreach (var propInfo in obj.GetType().GetProperties())
        {
            var newObject = Activator.CreateInstance(propInfo.PropertyType, propInfo.GetValue(obj));
            if (ObjectProcessing.ImplementsIEnumerable(newObject))
            {
                ObjectProcessing.ObjectQueue.Enqueue(newObject);
            }
        }

不幸的是,这不起作用。我不能使用 CreatInstance<T> 因为编译器似乎假定 T 是方法签名中的 T,它是源对象而不是目标对象。

这个问题看起来像一个 XY 问题。什么是 the XY Problem

您不需要创建对象的实例来查看它是否实现或 IEnumerable。让我以你目前所拥有的为基础

// This is the example object
public class MyClass {
    public IEnumerable A{ get;set;}
    public List<int> B{get;set;}
}

var myClass = new MyClass();
foreach (var propInfo in myClass.GetType().GetProperties()) {
    var typeOfProperty = propInfo.PropertyType;
    var isIEnuerableOrInheritingFromIt = typeof(IEnumerable).IsAssignableFrom(typeOfProperty);
    if (isIEnuerableOrInheritingFromIt) {
        var objectThatImplementsIEnumerable = propInfo.GetValue(myClass);
        // Do stuff with it
    }
}