将Class Member设置为Function

时间:2017-02-26 19:38:18

标签: c# reflection system.reflection

我有一个只通过反思与另一个类相互作用的类。我正在与之交互的这个类有一些代表,我正在尝试设置它们。这是他们的样子:

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

    public static OnSuccessDelegate OnSuccess;

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

以下是我的尝试:

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

我得到的错误是它无法将操作转换为对象。有关如何做到这一点的任何帮助?

1 个答案:

答案 0 :(得分:2)

你的课应该是:

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