【发布时间】:2021-11-13 00:39:08
【问题描述】:
是否可以将Lane 中的两个方法归结为一个泛型函数,可以通过传入接口和方法名称来重用?还是有更好的方法来解决这个问题?
上下文:我正在做一个节奏游戏,其中一个音符是通过key down和key up来判断的,目前我有以下接口和方法:
public interface IJudgeDown {
public Judgement JudgeDown(double inputBeat);
}
public interface IJudgeUp {
public Judgement JudgeUp(double inputBeat);
}
public class Lane {
private bool CheckKeyDown(double inputBeat) {
MusicNoteGameObject frontNote = visibleNotes.Peek();
IJudgeDown downObj = (IJudgeDown)frontNote;
Judgement j = downObj.JudgeDown(inputBeat);
// ... (identical to the rest of CheckKeyUp)
}
private bool CheckKeyUp(double inputBeat) {
MusicNoteGameObject frontNote = visibleNotes.Peek();
IJudgeUp upObj = (IJudgeUp)frontNote;
Judgement j = upObj.JudgeUp(inputBeat);
// ... (identical to the rest of CheckKeyDown)
}
}
MusicNoteGameObject 本身并没有实现这两个接口。但是,此基类针对实现了这两个接口的不同笔记类型进行了扩展(例如,TapNoteGameObject : MusicNoteGameObject, IJudgeDown, IJudgeUp)。
初次尝试失败:
public interface IJudge { } // Have an empty interface
public interface IJudgeDown : IJudge { ... }
public interface IJudgeUp : IJudge { ... }
private bool Judge<I>(Func<double, Judgement> method, double inputBeat) where I : IJudge {
MusicNoteGameObject frontNote = visibleNotes.Peek();
I obj = (I)frontNote; // This cast is invalid
Judgement j = obj.method(inputBeat); // How should I call the method on obj? Reflection?
// ...
}
要将正确的方法传递给Judge<>,我必须将frontNote 投射到Judge<> 之外,如下所示:
MusicNoteGameObject frontNote = visibleNotes.Peek();
IJudgeDown downObj = (IJudgeDown)frontNote;
Judge<IJudgeDown>(downObj.JudgeDown, inputBeat);
但是我不需要再传入IJudgeDown,我可以将Judge<> 的其余部分包装到一个函数中并调用它,从而不需要Judge<> 方法...
【问题讨论】:
标签: c# generics inheritance delegates