C# 在运行时c确定的泛型类型上调用非泛型方法#
我想对泛型类型调用非泛型方法。这是因为我知道T型在运行时肯定会有这样的方法。c#不允许这样做,所以我查找了解决方案,但我没有找到解决这个问题的方法 1) 我尝试使用动态类型,但遇到了一个问题,我仍然没有找到答案: 2) 我曾尝试定义一个接口,在该接口中我定义了在泛型方法中实例化的委托。这不起作用,因为在泛型_方法中,即使将委托传递给函数,我也无法访问该委托C# 在运行时c确定的泛型类型上调用非泛型方法#,c#,generics,C#,Generics,我想对泛型类型调用非泛型方法。这是因为我知道T型在运行时肯定会有这样的方法。c#不允许这样做,所以我查找了解决方案,但我没有找到解决这个问题的方法 1) 我尝试使用动态类型,但遇到了一个问题,我仍然没有找到答案: 2) 我曾尝试定义一个接口,在该接口中我定义了在泛型方法中实例化的委托。这不起作用,因为在泛型_方法中,即使将委托传递给函数,我也无法访问该委托 private interface MessageMethods { public delegate void MethodDele
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
}
专用接口消息方法
{
公共委托void MethodDelegate(DirectBuffer缓冲区、int偏移量、int actingBlockLength、int actingVersion);
}
私有静态T通用方法(字节[]固定内存,ref int offset),其中T:MessageMethods
{
MethodDelegate m=新的MethodDelegate(someFunctionsomewhere());
//Visual studio无法识别MethodDelegate是什么,因此这不起作用。
//SomeFunction Somewhere()不是泛型函数
}
我曾经研究过使用反射的问题,但这是我第一次处理泛型类型到这种程度,不幸的是,我很难理解如何在C#中使用反射。我还可以尝试什么?从代码的格式上看,还不完全清楚,但我认为这是您的问题: MethodDelegate是位于私有接口MessageMethods中的委托 您应该将接口公开,并在泛型_方法中使用以下语法:
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.
}
private static T generic_方法(byte[]pinned_memory,ref int offset),其中T:MessageMethods
{
MessageMethods.MethodDelegate m=newmessagemethods.MethodDelegate(somefunctionsomewhere);//另外,不要使用额外的(),因为您可能还不想调用该方法。
}
通用方法在哪里运行?它是某个更大类的一部分,是吗?是的,它是一个更大类的一部分。您需要提供一些更可编译的示例(可能再多5行就可以得到它了)。。。到目前为止,似乎与泛型无关-新的MessageMethods.MethodDelegate(someFunctionsomewhere)
应该可以解决您当前的问题。我这样做没有问题,但出于我自己的理解,为什么我不能将MessageMethods保持私有?我认为private仍然意味着同一类的成员可以访问它。是generic\u方法
在MessageMethods
中吗?没有generic\u方法和MessageMethods是同一类的一部分。我理解,由于泛型方法是静态的,它实际上并不与类的实例相关联,而非静态接口与类相关联,但泛型方法如何找到接口?这也是我需要了解的。我不完全确定内部类。但通常你会。