Steph
Steph

Reputation: 19

Set Class Member to Function

I have a class that interacts with another class solely through reflection. This class that I am interacting with has some delegates and I am trying to set them. Heres what they look like:

public class ClassThatIAmReflecting {
    public delegate void OnSuccessDelegate(bool value);

    public static OnSuccessDelegate OnSuccess;

    public void OnClassThatIAmReflectingSuccess(bool arg) {
        if(OnSuccess != null)
            OnSuccess(arg);
    }
} 

And here is what I am trying:

public class MyClass {

    void Init() {
        Type type = Type.GetType("ClassThatIAmReflecting");

        FieldInfo fieldInfo = type.GetField("OnSuccess", BindingFlags.Public | BindingFlags.Static);
        fieldInfo.SetValue(null, HandleOnSuccess);
    }

    void HandleOnSuccess(bool value) {
        // do stuff ...
    }
}

The error I am getting is that it cannot convert the action to a object. Any help on how I can do this?

Upvotes: 1

Views: 44

Answers (1)

Roman
Roman

Reputation: 12171

Your class should be:

public class MyClass
{

    public void Init()
    {
        Type type = typeof(ClassThatIAmReflecting);
        FieldInfo fieldInfo = type.GetField("OnSuccess", BindingFlags.Public | BindingFlags.Static);
        var fieldType = fieldInfo.FieldType;

        var methodInfo = this.GetType().GetMethod("HandleOnSuccess", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
        var del = Delegate.CreateDelegate(fieldType, this, methodInfo);

        fieldInfo.SetValue(null, del);

        //test
        ClassThatIAmReflecting.OnSuccess(true);
    }

    private void HandleOnSuccess(bool value)
    {
        Console.WriteLine("Called");
    }
}

Upvotes: 2

Related Questions