简体   繁体   English

如何强制.NET(C#)使用方法的非泛型重载?

[英]How Can I Force .NET (C#) to Use the non-generic overload of a method?

There's a method in the .NET Framework that has both generic and a non-generic version/overload. .NET Framework中有一个同时具有通用和非通用版本/重载的方法。 I want to force the compiler to generate my code using the non-generic version even if it can resolve the generic type at build time. 我想强制编译器使用非通用版本生成我的代码,即使它可以在构建时解析通用类型。

The specific method I want to use is Marshal::GetFunctionPointerForDelegate which, as of .NET 4.5.1, has a generic overload. 我要使用的特定方法是Marshal::GetFunctionPointerForDelegate ,从.NET 4.5.1开始,它具有一般的重载。 I want to use the original one (non-generic). 我想使用原始的(非泛型的)。

Also, if you could provide the solution (if any) in C++/CLI, it'd be much appreciated. 另外,如果您可以使用C ++ / CLI提供解决方案(如果有的话),将不胜感激。

UPDATE: There reason for this is that, if my program is ran in a computer that does not have .NET 4.5.1, my program will crash. 更新:这样做的原因是,如果我的程序是在没有.NET 4.5.1的计算机上运行的,则我的程序将崩溃。

It should be clear from the source code snippet posted by @elgonzo that the generic version is calling the non-generic version, otherwise you would have infinite recursion. 从@elgonzo发布的源代码片段中应该清楚,通用版本正在调用非通用版本,否则您将具有无限递归。

Therefore, you too can call the non-generic version. 因此,您也可以调用非通用版本。 The trick is making the non-generic version a perfect match. 诀窍是使非通用版本完美匹配。

C#: C#:

Marshal.GetFunctionPointerForDelegate( (Delegate)(object) mydel );

C++/CLI: C ++ / CLI:

Marshal::GetFunctionPointerForDelegate( dynamic_cast<Delegate^>(safe_cast<Object^>(mydel)) );

It does not really matter whether you use the generic or the non-generic variant of the Marshall.GetFunctionPointerForDelegate method. 使用Marshall.GetFunctionPointerForDelegate方法的泛型或非泛型变量并不重要。

The only thing Marshall.GetFunctionPointerForDelegate<TDelegate>(...) does is calling the non-generic Marshal.GetFunctionPointerForDelegate(...) method. Marshall.GetFunctionPointerForDelegate <TDelegate>(...)唯一要做的就是调用非通用的Marshal.GetFunctionPointerForDelegate(...)方法。

As can be seen in the .NET framework reference source code , the implementation of GetFunctionPointerForDelegate<TDelegate> is just: 从.NET框架参考源代码中可以看出, GetFunctionPointerForDelegate <TDelegate>的实现只是:

public static IntPtr GetFunctionPointerForDelegate<TDelegate>(TDelegate d)
{
    return GetFunctionPointerForDelegate((Delegate)(object)d);
}

Regarding your update 关于您的更新

UPDATE: There reason for this is that, if my program is ran in a computer that does not > have .NET 4.5.1, my program will crash. 更新:这样做的原因是,如果我的程序在没有> .NET 4.5.1的计算机上运行,​​则我的程序将崩溃。

Set the target framework of your project to a .NET version prior to 4.5.1 (for example, if your project is required to run on .NET 3.5, then set the target framework of your project to .NET 3.5.) 将项目的目标框架设置为4.5.1之前的.NET版本(例如,如果您的项目要求在.NET 3.5上运行,则将项目的目标框架设置为.NET 3.5。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM