【发布时间】:2015-07-09 20:34:07
【问题描述】:
我想在泛型类型上调用非泛型方法。这是因为我知道 T 类型在运行时肯定会有所说的方法。 c# 不允许这样做,所以我查找了解决方案,但没有找到解决此问题的方法。
1) 我尝试使用动态类型,但遇到了一个我仍然没有找到答案的问题:one or more types required to compile a dynamic expression c#
2) 我尝试定义一个接口,在该接口中定义了我在 generic_method 中实例化的委托。这不起作用,因为在 generic_method 中我无法访问委托,即使我将它传递给函数。
private interface MessageMethods
{
public delegate void MethodDelegate(DirectBuffer buffer, int offset, int actingBlockLength, int actingVersion);
}
private static T generic_method<T>(byte[] pinned_memory, ref int offset) where T: MessageMethods
{
MethodDelegate m = new MethodDelegate(someFunctionSomewhereElse());
// Visual studio does not recognize what MethodDelegate is, so this does not work.
// someFunctionSomewhereElse() is NOT generic
}
我已经研究过使用反射的问题,但这是我第一次处理泛型类型到这种程度,不幸的是我很难理解如何在 C# 中使用反射。我还能尝试什么?
【问题讨论】:
-
generic_method<T>住在哪里?它是某个更大课程的一部分,是吗? -
是的,它是一个更大的类的一部分
-
您需要提供更多可编译的示例(可能再多 5 行就可以了)...到目前为止看起来与泛型无关 -
new MessageMethods.MethodDelegate(someFunctionSomewhereElse)应该可以解决您当前的问题。