c# - 使用反射将项目添加到通用列表/集合

标签 c# generics reflection

我想使用反射将项目添加到通用列表。在“DoSomething”方法中,我试图完成以下行,

pi.PropertyType.GetMethod("Add").Invoke(??????)

但我遇到了不同类型的错误。

下面是我的完整代码

public class MyBaseClass
{        
    public int VechicleId { get; set; }        
}    
public class Car:MyBaseClass
{
    public string Make { get; set; }
}    
public class Bike : MyBaseClass
{
    public int CC { get; set; }
}        
public class Main 
{
    public string AgencyName { get; set; }
    public MyBaseCollection<Car> lstCar {get;set;}

    public void DoSomething()
    {
        PropertyInfo[] p =this.GetType().GetProperties();
        foreach (PropertyInfo pi in p)
        {
            if (pi.PropertyType.Name.Contains("MyBaseCollection"))
            {
                //Cln contains List<Car>
                IEnumerable<MyBaseClass> cln = pi.GetValue(this, null) as IEnumerable<MyBaseClass>;

                **//Now using reflection i want to add  a new car to my object this.MyBaseCollection**
                pi.PropertyType.GetMethod("Add").Invoke(??????)
            }
        }    
    }
}

有什么想法/建议吗?

最佳答案

我想你想要:

// Cast to IEnumerable<MyBaseClass> isn't helping you, so why bother?
object cln = pi.GetValue(this, null);

// Create myBaseClassInstance. 
// (How will you do this though, if you don't know the element-type?)
MyBaseClass myBaseClassInstance = ...

// Invoke Add method on 'cln', passing 'myBaseClassInstance' as the only argument.
pi.PropertyType.GetMethod("Add").Invoke(cln, new[] { myBaseClassInstance } );

由于您不知道集合的元素类型是什么(可能是汽车、自行车、自行车等),您会发现很难找到有用的转换。例如,虽然您说该集合肯定会实现 IList<SomeMyBaseClassSubType> ,自 IList<T> 以来,这并没有多大帮助不是协变的。当然,转换到IEnumerable<MyBaseClass> 应该成功,但这对您没有帮助,因为它不支持突变。另一方面,如果您的集合类型实现了非泛型 IListICollection类型,转换到那些可能会派上用场。

但是如果您确定该集合将实现 IList<Car> (即你事先知道集合的元素类型),事情更容易:

// A much more useful cast.
IList<Car> cln = (IList<Car>)pi.GetValue(this, null);

// Create car.
Car car = ...

// The cast helped!
cln.Add(car);

关于c# - 使用反射将项目添加到通用列表/集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4910256/

相关文章:

C# 反射类型参数数量可变的类型

c# - 从模型中添加新项目计数

java - 为什么不允许使用不同的泛型类型作为参数进行重载?

c# - Entity Framework 异步问题上下文或查询?

java - 类型转换通用

Swift:通用协议(protocol)无法使用类型的参数列表调用

c# - 如何以编程方式分配 .Net 属性?

c# - 无法为当前正在执行的程序集中未定义的类型获取 Type 类的实例

c# - 使用存储过程或 C# 同步 SQL Server 2014 和 SQL Server 2014 Express 数据库

c# - 是否有一些调试工具可以在平面表格中显示结果