문제

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