【问题标题】:calling nongeneric method on generic type determined at runtime c#在运行时确定的泛型类型上调用非泛型方法 c#
【发布时间】: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&lt;T&gt; 住在哪里?它是某个更大课程的一部分,是吗?
  • 是的,它是一个更大的类的一部分
  • 您需要提供更多可编译的示例(可能再多 5 行就可以了)...到目前为止看起来与泛型无关 - new MessageMethods.MethodDelegate(someFunctionSomewhereElse) 应该可以解决您当前的问题。

标签: c# generics


【解决方案1】:

从代码的格式来看还不是很清楚,但我认为这是你的问题:

MethodDelegate 是一个位于私有接口 MessageMethods 中的委托。

您应该公开您的接口,并在您的 generic_method 中使用以下语法:

private static T generic_method<T>(byte[] pinned_memory, ref int offset) where T : MessageMethods
{
    MessageMethods.MethodDelegate m = new MessageMethods.MethodDelegate(someFunctionSomewhereElse); // also, don't use the extra (), because you probably don't want to call the method yet.
}

【讨论】:

  • 我这样做没有问题,但根据我自己的理解,为什么我不能将 MessageMethods 保密?我认为 private 仍然意味着同一类的成员可以访问它。
  • generic_methodMessageMethods 内部吗?
  • 没有 generic_method 和 MessageMethods 属于同一类。我知道,由于 generic_method 是静态的,它实际上并没有与类的实例相关联,而非静态接口与类相关联,但是 generic_method 又如何找到接口?
  • 这也是我需要了解的。我不完全确定内部类。但通常你会。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-23
  • 1970-01-01
  • 2021-02-16
  • 1970-01-01
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多