C#通用方法和动态类型问题

Kar*_*lta 3 c# generics parameters types

我有一个声明如下的泛型方法:

public void Duplicate<EntityType>() { ... }
Run Code Online (Sandbox Code Playgroud)

所以,一般来说使用它我只需要说:

myObject.Duplicate<int>()
Run Code Online (Sandbox Code Playgroud)

但是在这里,我想要做的是通过变量传递类型,但它不起作用,这是我尝试这样做的方式:

Type myType = anObject.GetType();
myObject.Duplicate<myType>();
Run Code Online (Sandbox Code Playgroud)

如果有人可以帮助我?

预先感谢.

Jon*_*eet 12

你必须使用反射,基本上:

MethodInfo method = typeof(...).GetMethod("Duplicate");
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(myObject, null);
Run Code Online (Sandbox Code Playgroud)