泛型在C#中,使用一个变量作为参数的类型 [英] Generics in C#, using type of a variable as parameter

查看:680
本文介绍了泛型在C#中,使用一个变量作为参数的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用的方法

 布尔DoesEntityExist< T>(GUID GUID,ITransaction事务),其中T:IGloballyIdentifiable;
 

以下面的方式如何使用方法:

 键入T = entity.GetType();
DoesEntityExist< T>(entityGuid,交易);
 

我不断收到foollowing编译错误:

  

类型或命名空间名称'T'可以   未找到(是否缺少使用   指令或程序集引用?)

  DoesEntityExist< MyType的>(entityGuid,交易);
 

完美的作品,但我不希望使用if指令用一个单独的类型名称,每次调用该方法。

解决方案

有关仿制药的一点是给的编译时间的类型安全 - 这意味着,类型需要在编译时是已知的。

您的可以的调用通用的方法,与只知道在执行时的类型,但你必须使用反射:

  //对于非公共方法,你需要指定绑定标志太
MethodInfo的方法=的GetType()。GetMethod的(DoesEntityExist)
                             .MakeGenericMethod(新类型[]【T】);
method.Invoke(这一点,新的对象[] {entityGuid,成交});
 

伊克。

你可以让你的呼叫的方法,而不是通用的,并通过在你的类型参数作为类型参数,推栈中的一项决定水平呢?

如果你能给我们介绍一下你在做什么的详细信息,这将有助于。有时你可能需要使用反射同上,但如果你选择合适的点来做到这一点,你可以确保你只需做一次,并让低于该点的一切使用正常方式的类型参数。

I have a generic method

bool DoesEntityExist<T>(Guid guid, ITransaction transaction) where T : IGloballyIdentifiable;

How do I use the method in the following way:

Type t = entity.GetType();
DoesEntityExist<t>(entityGuid, transaction);

I keep receiving the foollowing compile error:

The type or namespace name 't' could not be found (are you missing a using directive or an assembly reference?)

DoesEntityExist<MyType>(entityGuid, transaction);

works perfectly but I do not want to use an if directive to call the method with a separate type name every time.

解决方案

The point about generics is to give compile-time type safety - which means that types need to be known at compile-time.

You can call generic methods with types only known at execution time, but you have to use reflection:

// For non-public methods, you'll need to specify binding flags too
MethodInfo method = GetType().GetMethod("DoesEntityExist")
                             .MakeGenericMethod(new Type[] { t });
method.Invoke(this, new object[] { entityGuid, transaction });

Ick.

Can you make your calling method generic instead, and pass in your type parameter as the type argument, pushing the decision one level higher up the stack?

If you could give us more information about what you're doing, that would help. Sometimes you may need to use reflection as above, but if you pick the right point to do it, you can make sure you only need to do it once, and let everything below that point use the type parameter in a normal way.

这篇关于泛型在C#中,使用一个变量作为参数的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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