委托(delegate)的使用遵循与调用方法相同的规则 - 如果您被允许显式调用该方法,则只能通过委托(delegate)引用该方法,这意味着您不能从静态方法引用非静态方法,即使如果您实际上不调用它。有解决办法吗?
这是执行保龄球套路时使用的一些代码,注释中显示了我理想的代码行。我被迫通过静态调用(和匿名静态方法声明)来使 Frame 类代码符合我的喜好:
public int FrameScore()
{
return scorer[FrameType()](this);
// I would like it to be
// return this.scorer[FrameType()]();
}
static Dictionary<LinkedFrame.FrameTypeEnum, Func<LinkedFrame, int>> scorer =
new Dictionary<LinkedFrame.FrameTypeEnum, Func<LinkedFrame, int>>()
{
{LinkedFrame.FrameTypeEnum.Strike, frame => frame.StrikeScore()},
{LinkedFrame.FrameTypeEnum.Spare, frame => frame.SpareScore()},
{LinkedFrame.FrameTypeEnum.Regular, frame => frame.RegularScore()}
// I would like an element to be
// {LinkedFrame.FrameTypeEnum.Strike, StrikeScore}
};
private int RegularScore()
{
return this.Sum;
}
private int SpareScore()
{
...
}
private int StrikeScore()
{
...
}
因此在某些情况下,在静态上下文中推理非静态方法是有意义的。有办法做到这一点吗?
最佳答案
也许开放实例委托(delegate)会有所帮助?
根据 MSDN: Delegate Class :
When a delegate represents an instance method closed over its first argument (the most common case), the delegate stores a reference to the method's entry point and a reference to an object, called the target, which is of a type assignable to the type that defined the method. When a delegate represents an open instance method, it stores a reference to the method's entry point. The delegate signature must include the hidden this parameter in its formal parameter list; in this case, the delegate does not have a reference to a target object, and a target object must be supplied when the delegate is invoked.
归根结底,您可以使用显式 this
参数偷偷地将实例方法转换为静态方法。你可以在这里看到它是如何完成的:Simon Cooper: Introduction to open instance delegates
关于c# - 您可以在静态上下文中引用非静态方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7625474/