委托给实例方法不能有 null 'this'

Delegate to an instance method cannot have null #39;this#39;(委托给实例方法不能有 null this)

本文介绍了委托给实例方法不能有 null 'this'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 C# .NET 2.0 应用程序,其中在运行时根据环境加载两个 DLL 之一.两个 DLL 都包含相同的函数,但它们没有链接到相同的地址偏移量.我的问题是关于我的应用程序代码中的函数委托.

I am developing a C# .NET 2.0 application wherein at run-time one of two DLLs are loaded depending on the environment. Both DLLs contain the same functions, but they are not linked to the same address-offset. My question is regarding the function delegates in my application code.

public class MyClass
{
    public delegate int MyFunctionDelegate(int _some, string _args);

    public MyFunctionDelegate MyFuncToCallFrmApp;

    public MyClass() : base()
    {
        this.MyFuncToCallFrmApp = new MyFunctionDelegate(this.MyFuncToCallFrmApp); // <-- Exception thrown here.
    }

    public SomeFunction()
    {
        MyFuncToCallFrmApp(int _someOther, string _argsLocal);
    }
}

当我的代码执行时,我得到一个 ArgumentException 委托给实例方法不能有 null 'this'".我做错了什么?

When my code executes I get an ArgumentException of "Delegate to an instance method cannot have null 'this'." What am I doing wrong?

推荐答案

您需要为您的委托变量分配一个有效的函数(由动态加载的 dll 中的某个类托管).如果函数是具有同名的类的静态方法,这很简单:

You need to assign a valid function (hosted by some class in the dynamically loaded dll) to your delegate variable. If the functions are static methods on classes with the same name, this is straightforward:

public MyClass() {
    this.MyFuncToCallFrmApp = ExternalClass.Function;
}

如果函数是同名类的实例方法,只需创建一个实例并做同样的事情(还要注意,只要委托在范围内,它将阻止 ExternalClass实例被垃圾收集 - 您可能希望将实例存储为成员变量以使其更清晰):

If the functions are instance methods of classes with the same name, just create an instance and do the same thing (also note that as long as the delegate is in scope, it will prevent the ExternalClass instance from being garbage-collected - you may want to store the instance as a member variable to make that clearer):

public MyClass() {
    this.MyFuncToCallFrmApp = new ExternalClass().Function;
}

如果动态加载的类有不同的名称,您需要确定调用哪个类 - 在本例中,我使用布尔成员变量来决定是否使用默认程序集的类:

If the dynamically-loaded classes have different names, you'll need to determine which one to call - in this example, I'm using a boolean member variable to decide whether or not to use a default assembly's class:

public MyClass() {
    if (this.defaultAssembly) {
        this.MyFuncToCallFrmApp = ExternalClass1.Function;
    } else {
        this.MyFuncToCallFrmApp = ExternalClass2.Function;
    }
}

这篇关于委托给实例方法不能有 null 'this'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:委托给实例方法不能有 null 'this'

基础教程推荐