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

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

问题描述

我有一个通用的方法

boolDoesEntityExist(Guid guid, ITransaction transaction) where T : IGloballyIdentifiable;

我如何以如下方式使用该方法:

Type t = entity.GetType();实体存在吗(entityGuid, 交易);

我不断收到愚蠢的编译错误:

<块引用>

类型或命名空间名称 't' 可以找不到(您是否错过了使用指令或程序集引用?)

DoesEntityExist(entityGuid, transaction);

工作完美,但我不想每次都使用 if 指令来调用具有单独类型名称的方法.

解决方案

关于泛型的要点是提供编译时类型安全——这意味着需要在编译时知道类型.

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

//对于非公共方法,您也需要指定绑定标志MethodInfo method = GetType().GetMethod("DoesEntityExist").MakeGenericMethod(new Type[] { t });method.Invoke(this, new object[] { entityGuid, transaction });

好的.

你能否让你的调用方法变得通用,并将你的类型参数作为类型参数传递,将决策推到堆栈上一层?

如果您能向我们提供有关您在做什么的更多信息,那将会有所帮助.有时你可能需要像上面一样使用反射,但是如果你选择了正确的点来做,你可以确保你只需要做一次,并且让该点以下的一切都以正常方式使用类型参数.

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天全站免登陆