您可以使用泛型方法在C#中,如果类型是未知的,直到运行时? [英] Can you use generics methods in C# if the type is unknown until runtime?

查看:223
本文介绍了您可以使用泛型方法在C#中,如果类型是未知的,直到运行时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最简单的方式来解释我的意思是一个代码示例。这并不编译,但有什么办法来实现这种效果:

Easiest way to explain what I mean is with a code sample. This doesn't compile, but is there any way to achieve this effect:

foreach(Type someType in listOfTypes)
{
    SomeMethod<someType>();
}



将是非常方便的,如果这样做的工作,但事实并非如此。是否有另一种方式来实现上述相同的事情,为什么不C#允许,要成为一个合法声明

Would be really convenient if that would work, but it doesn't. Is there another way to achieve the same thing as above, and why doesn't C# allow for that to be a legal statement?

编辑:好像只有这样才能做到这一点是通过反射这可能是我们的需要太慢。为何有没有内置的,是否这样的事情是在作品的有效方式任何有识之士C#4.0?

Seems like the only way to do this is via reflection which may be too slow for our needs. Any insight on why there's not an efficient way built in and whether something like this is in the works for C# 4.0?

推荐答案

您可以使用反射。假设当前对象包含的someMethod()方法,代码这样做会是这样的:

You can use reflection. Assuming the current object contains the SomeMethod() method, the code to do so would look like this:

GetType().GetMethod("SomeMethod").
    MakeGenericMethod(new Type[] { someType }).Invoke(this, null);

请注意,如果的someMethod()非-public,你的代码可能无法在低信任环境中执行。

Note that if SomeMethod() is non-public, your code may not execute in lower-trust environments.

这篇关于您可以使用泛型方法在C#中,如果类型是未知的,直到运行时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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