Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用T属性创建具有属性值的属性类型的新对象?_C#_Oop_Generics_Reflection_Activator - Fatal编程技术网

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

C# 使用T属性创建具有属性值的属性类型的新对象?,c#,oop,generics,reflection,activator,C#,Oop,Generics,Reflection,Activator,我需要一种方法将T类型的对象的属性转换为T类型的对象,以及T中的值。我这样做的原因是,我可以检查该属性是否为IEnumerable(列表、数组等)或是否继承IEnumerable,如果是,那么我需要将IEnumerable作为要处理的对象传递。到目前为止 foreach (var propInfo in obj.GetType().GetProperties()) { var newObject = Activator.CreateInstance(pro

我需要一种方法将T类型的对象的属性转换为T类型的对象,以及T中的值。我这样做的原因是,我可以检查该属性是否为IEnumerable(列表、数组等)或是否继承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,它是源对象而不是目标对象。

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

您不需要创建对象的实例来查看它是否实现或是
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
    }
}
//这是示例对象
公共类MyClass{
公共IEnumerable A{get;set;}
公共列表B{get;set;}
}
var myClass=新的myClass();
foreach(myClass.GetType().GetProperties()中的var propInfo){
var typeOfProperty=propInfo.PropertyType;
变量IseUnerableOrInheritingFromit=typeof(IEnumerable)。IsAssignableFrom(typeOfProperty);
如果(是否可从中删除或写入){
var objectThatImplementsIEnumerable=propInfo.GetValue(myClass);
//用它做点什么
}
}

请提供一个清晰的解释,说明您想要实现的目标、代码中的目标、预期行为与您观察到的情况的描述这看起来像一个X-Y问题。为什么需要创建属性的实例以查看它是否继承IEnumerable?为清晰起见,请进行编辑。我已经有了检查的方法,但是如果它返回true,我需要将参数作为独立于其父类的对象传递。@HenryPuspurs,请记住,如果使用
Activator.CreateInstance
创建一个
新的
实例,它将与原始对象实例不同,我不需要它,我需要它是一个属性类型的新对象,具有属性的值,独立于原始对象。我已经可以检查并返回true或false,但如果为true,我需要将该参数作为对象传递。@HenryPuspurs,您已经可以在答案中看到如何获取该对象。进一步询问是否有其他不清楚的部分,我会将其标记为正确。对于那些阅读修正的人来说,有效的修正是“var newObject=Activator.CreateInstance(propInfo.PropertyType,propInfo.GetValue(obj));”需要是'var newObject=propInfo.GetValue(obj);'