为什么我不能使用仿制药Type.GetType()? [英] Why I cannot use Type.GetType() in generics?

查看:146
本文介绍了为什么我不能使用仿制药Type.GetType()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过使用某些类型的字符串表示改掉一些参考。但是编译器是不是让我做,我想在泛型方法的情况下的方式。我想这样的:

I am trying to get rid of some references by using string representation of certain types. But compiler is not letting me do it the way I want in case of generic methods. I tried this:

IContainer container = components as IContainer;
Type type = Type.GetType("MyNamespace.MyType");
foreach (var component in container.Components.OfType<Type.GetType("MyNamespace.MyType")>()) {
    ...
}

和这样的:

foreach (var component in container.Components.OfType<type>()) {
    ...
}

对于第一个循环我得到这个:操作'<'不能应用于类型为方法组'和'的System.Type'的操作数,第二个变量是超出范围的有些道理的。为什么会出现这种情况,是有办法解决它?在此先感谢。

For the first loop I get this: "Operator '<' cannot be applied to operands of type 'method group' and 'System.Type', and for the second the variable is out of scope for some reason. Why is this happening and is there a way around it? Thanks in advance.

推荐答案

您可以使用Type.MakeGenericType例:

You can use Type.MakeGenericType. Example:

Type.GetType("YourGenericType").MakeGenericType(Type.GetType("yourTypeParameter"))

对于从一个字符串确定的typeparameter一个列表示例

Example for a List with a typeparameter determined from a string:

typeof(List<>).MakeGenericType(Type.GetType("System.String"))

这给你一样

typeof(List<string>)

但你仍然不能使用类型实例调用Enumerable.OfType。你可以使用这样的事情,而不是:

But you still can't use a Type instance to call Enumerable.OfType. You could use something like this instead:

foreach (var component in container.Components.Where(o => o.GetType().IsAssignableFrom(yourType))) 
{
    //...
}

当然,这让我们快速凌乱,所以我会考虑改变你的做法。为什么你wan't使用字符串?

Of course, this get's messy quickly, so I would consider changing your approach. Why do you wan't to use strings?

这篇关于为什么我不能使用仿制药Type.GetType()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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