将对象传递给泛型方法 [英] Passing an object to a generic method
问题描述
说我们有:
Say we have :
public void method<T>(T obj)
{
// some stuff done on the obj
}
并且我们已经反序列化了一个对象,我们需要传递
And we have deserialized an object and we need to pass
object obj = CreateObject(bytearray); // serialized byte[] of object
method(obj);
现在的问题是method
需要知道其工作的对象类型(内部泛型),但是我们传递的是object
,因此它将失败.但是,CreateObject
方法可以确定类型,并且可以毫无问题地重新创建原始类型.
问题是:我们如何才能以某种方式将类型信息提供给method
,以便它在运行时不会中断?
Now the problem is that method
needs to know the object type for it to work (internal generics) but we are passing an object
, so it will fail. However the CreateObject
method can determine the type and it recreates the original without problem.
The question is : how can we somehow give the type information to method
so it doesn''t break at runtime?
推荐答案
我想您想使用泛型语法传递类型.如果是这样,您可以使用以下方式传递它:
Hi,
I presume you want to pass the type using the Generics syntax. If so, you can pass it using something like this:
Int32 iObj=0;
method<int32>(iObj);
或
or
Stack sObj = new Stack();
method<stack>(sObj);
我不确定您的观点是否是将类型发送到方法"方法的另一种方法?
干杯
I''m not sure if your point is another mean of sending type to the ''method'' method?
Cheers
找到的解决方案是:
Found the solution as :
object obj = CreateObject(bytearray);
var mi = this.GetType().GetMethod("method", BindingFlags.Instance | BindingFlags.NonPublic);
var m = mi.MakeGenericMethod(new Type[] { obj.GetType() });
m.Invoke(this, new object[] { obj }); // instead of method(obj);
这篇关于将对象传递给泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!