【问题标题】:Delegate definitions - in/outside method makes any difference?委托定义 - 内部/外部方法有什么不同吗?
【发布时间】:2012-06-29 15:16:43
【问题描述】:

如标记,我正在使用 Mono,而不是 .NET,如果重要的话。

在使用委托时,我对范围的最佳实践感到困惑。请注意,在此示例中,autoOrientationsautoRotationSetups 将在类中的其他位置(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 可能会澄清这一点,我想我很清楚,但我对它的理解还不够好,还不能完全自信。另外,我不知道有任何其他可能的原因导致这种方式或其他方式,因此这个问题。

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

【问题讨论】:

    标签: c# delegates mono


    【解决方案1】:

    这两种方法之间有什么不同之处吗?

    当您通过 lambda 表达式创建匿名方法时,编译器只会为您创建一个方法。实际上,这两个版本可能几乎没有区别。

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

    在我目前的知识水平上,我最关心的变量是存储在错误的内存区域中

    我不会这么担心——这并不是说有“正确”和“错误”的记忆区域......

    【讨论】:

    • 谢谢!提到闭包把我带到了这里,这对我很有帮助:diditwith.net/…
    • @Jessy 请注意,第一个选项并不意味着您一定会得到一个闭包 - 只有当您使用在匿名方法之外定义的变量时才会发生这种情况。如果您将所有内容都保留在本地(即:与“普通方法”相同),则两者实际上是相同的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多