在ICollection<>上执行.Add()方法

时间:2015-02-15 22:04:59

标签: c# .net

我有一个 Some Type 的对象,我知道它实现了ICollection<T>。我不知道(在编译时)泛型集合的类型是什么 - 它几乎可以是任何东西。

我有一个类型为T的新对象,但我仍然(在编译时)不知道该类型是什么。

我想做这样的事情:

object myCollection; // I know it implements ICollection<T>, but nothing more
object newObject; // I know that newObject.GetType() matches T, but nothing more

myCollection.Add( newObject ); // This syntax is clearly ludicrous, but...

如何在不使用反射的情况下使最后一行工作(.Add)?现在,我反映了从

构造的Type的MethodInfo
object myCollection;
object newObject;

var typ = newObject.GetType();
var colTyp = typeof( ICollection<> ).MakeGenericType( new Type[] { typ } );
var mi = colTyp.GetMethodInfo( "Add" );
mi.Invoke( myCollection, new object[] { newObject } );

这似乎是一场表演的噩梦,即使我根据newObject.GetType()进行了一些缓存。

有更好的方法吗?

编辑:不使用动态对象

0 个答案:

没有答案
相关问题