質問

I am creating a custom BindingSource and would like to persist a MethodInfo as a private field. The problem, in code:

public class MyBindingSource : BindingSource
{

    private MethodInfo MyMethod= null;

    protected override void OnBindingComplete(BindingCompleteEventArgs e)
    {
         this.MyMethod = GetMyMethod();
         //MyMethod is not null here
    }

    void UseMyMethod (object value)
    {
        MyMethod.Invoke(SomeObject, new object[] { value });
        //MyMethod is null here, exception thrown.
    }

}

I successfully store the MethodInfo, however, when i try to use it, it ends up being null. No special constructor is being called (overriding the field). OnBindingComplete is not called twice. Nothing seems to imply that something else is setting it to null.

役に立ちましたか?

解決

Most probably you are accessing UseMethod before OnBindingComplete

But in any case, to prevent this, you can do something like this:

public class MyBindingSource : BindingSource
{
    private MethodInfo _myMethod = null;

    private MethodInfo MyMethod
    {
        get
        {
            if(_myMethod != null) return _myMethod;

            _myMethod = GetMyMethod();
            return _myMethod;
        }
    }

    protected override void OnBindingComplete(BindingCompleteEventArgs e)
    {
    }

    void UseMyMethod (object value)
    {
        MyMethod.Invoke(SomeObject, new object[] { value });
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top