委托定义 - in / outside方法有什么区别?

时间:2012-06-29 15:16:43

标签: c# delegates mono

如果标记的话,我正在使用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可以清楚地说明这一点,我认为我很清楚,但我还是不太了解它还没有完全自信。另外,我不知道有任何其他可能的原因,因此这个问题。

我最近因为人们认为他们是主观的而被关闭了问题,所以,尽管我重视你的意见,“不。”是一个可以接受的答案。 “是”可能需要进一步解释这不是纯粹的风格选择。

1 个答案:

答案 0 :(得分:3)

  

这两种方法之间是否有任何不同的发生?

当您通过lambda表达式创建匿名方法时,编译器只为您创建一个方法。实际上,这两个版本可能差别很小。

主要区别在于,通过允许编译器创建匿名方法,您可以打开在Awake()方法中使用本地定义变量的闭包的功能。这可能是一件好事,也可能是坏事,这取决于你想要什么 - 因为它可能会导致生成额外的类来保存变量。

  

在我目前的知识水平上,我主要关注生活在错误记忆区域的变量

我不会这么担心 - 这不像是有一个“正确”和“错误”的记忆区域......