【发布时间】:2012-06-29 15:16:43
【问题描述】:
如标记,我正在使用 Mono,而不是 .NET,如果重要的话。
在使用委托时,我对范围的最佳实践感到困惑。请注意,在此示例中,autoOrientations 和 autoRotationSetups 将在类中的其他位置(Awake() 之外)使用。还要注意在使用Unity时,你经常use Awake() where you might otherwise be using a constructor:
List<ScreenOrientation> autoOrientations;
Dictionary<ScreenOrientation, Action> autoRotationSetups;
void Awake() {
var verticalOrientations = new List<ScreenOrientation>(
new []{ScreenOrientation.Portrait, ScreenOrientation.PortraitUpsideDown});
Action setAutoRotationsToVertical = () => {
// I don't think this defintion is important for this question,
// but it does use the just-defined List.
};
var horizontalOrientations = new List<ScreenOrientation>(
new []{ScreenOrientation.LandscapeLeft, ScreenOrientation.LandscapeRight});
Action setAutoRotationsToHorizontal = () => {// See last comment.
};
autoRotationSetups = new Dictionary<ScreenOrientation, Action>() {
{ScreenOrientation.Portrait, setAutoRotationsToVertical},
{ScreenOrientation.PortraitUpsideDown, setAutoRotationsToVertical},
{ScreenOrientation.LandscapeLeft, setAutoRotationsToHorizontal},
{ScreenOrientation.LandscapeRight, setAutoRotationsToHorizontal},
}; //...
或者,我可以定义类方法,然后将它们分配给委托。这种改变看起来像:
List<ScreenOrientation> verticalOrientations, horizontalOrientations;
void SetAutoRotationsToVertical() {}
void SetAutoRotationsToHorizontal() {}
void Awake() {
Action setAutoRotationsToVertical = SetAutoRotationsToVertical;
Action setAutoRotationsToHorizontal = SetAutoRotationsToHorizontal; //...
这两种方法之间有什么不同之处吗?以我目前的知识水平,我最关心的变量是存储在错误的记忆区域; The Truth About Value Types 可能会澄清这一点,我想我很清楚,但我对它的理解还不够好,还不能完全自信。另外,我不知道有任何其他可能的原因导致这种方式或其他方式,因此这个问题。
我最近收到一些问题,因为人们认为这些问题是主观的,所以尽管我很重视你的意见,但“不”。将是一个可以接受的答案。 “是”可能需要进一步解释这不是纯粹的风格选择。
【问题讨论】: