且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

泛型在C#中,使用一个变量作为参数的类型

更新时间:2022-12-12 12:22:29

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

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

  //对于非公共方法,你需要指定绑定标志太
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.