Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
    }
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
685 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;
}

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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...