我正在创建一个自定义的 BindingSource,并希望将 MethodInfo 保留为私有(private)字段。 代码中的问题:
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.
}
}
我成功地存储了 MethodInfo,但是,当我尝试使用它时,它最终为空。 没有调用特殊的构造函数(覆盖字段)。 OnBindingComplete 不会被调用两次。 似乎没有任何东西暗示其他东西将其设置为空。
最佳答案
很可能您在 OnBindingComplete
之前访问 UseMethod
但无论如何,为了防止这种情况发生,您可以这样做:
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 });
}
}
关于c# - 将 MethodInfo 保留为属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12552824/