C#泛型方法和动态类型问题 [英] C# Generic method and dynamic type problem

查看:183
本文介绍了C#泛型方法和动态类型问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用方法声明如下:

I have a generic method declared as follow :

public void Duplicate<EntityType>() { ... }

因此,通常要使用它,我只需要说一遍即可:

So, generally to use it I simply need to do say :

myObject.Duplicate<int>()

但是,在这里,我想做的是通过变量传递类型,但这是行不通的,这是我尝试执行的操作:

But here, what I'd like to do is pass the type by a variable, but it doesn't work, here is how I try to do this :

Type myType = anObject.GetType();
myObject.Duplicate<myType>();

如果有人可以帮助我?

谢谢.

推荐答案

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

You have to use reflection, basically:

MethodInfo method = typeof(...).GetMethod("Duplicate");
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(myObject, null);

这篇关于C#泛型方法和动态类型问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆