【问题标题】:Using a property of T to create a new object of the property type with the property values?使用 T 的属性创建具有属性值的属性类型的新对象?
【发布时间】:2020-10-12 13:42:41
【问题描述】:

我需要一种方法将 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,它是源对象而不是目标对象。

【问题讨论】:

  • 请提供您想要实现的目标的清晰说明、代码中的minimal, complete example、预期行为与您观察到的行为的描述
  • 这看起来像是一个 X-Y 问题。为什么要创建属性的实例,看是否继承了IEnumerable?
  • 为清晰起见进行了编辑。我已经有了检查方法,但如果它返回 true,我需要将参数作为独立于其父类的对象传递。
  • @HenryPuspurs,请记住,如果您使用 Activator.CreateInstance 创建 new 实例,它将与原始对象实例不同
  • 我不需要它,我需要它是属性类型的新对象,具有属性的值,独立于原始对象。

标签: c# oop generics reflection activator


【解决方案1】:

这个问题看起来像一个 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
    }
}

【讨论】:

  • 和上面的 cmets 一样。我已经可以检查并返回 true 或 false,但如果为 true,我需要将该参数作为对象传递。
  • @HenryPuspurs,您已经可以在答案中看到如何获取对象。进一步询问是否还有其他不清楚的部分
  • 好的,我会把它标记为正确的。对于那些阅读有效更正的人来说,'var newObject = Activator.CreateInstance(propInfo.PropertyType, propInfo.GetValue(obj));'需要是 'var newObject = propInfo.GetValue(obj);'
猜你喜欢
  • 2021-07-29
  • 1970-01-01
  • 2010-09-19
  • 1970-01-01
  • 1970-01-01
  • 2019-02-01
  • 1970-01-01
  • 2017-08-11
相关资源
最近更新 更多