使用闭包跟踪变量:好主意或肮脏的把戏? [英] Using Closures to keep track of a variable: Good idea or dirty trick?

查看:178
本文介绍了使用闭包跟踪变量:好主意或肮脏的把戏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我有一个需要能够跟踪值类型的对象这是另一个对象,不能没有具有这些属性的实现一个接口的IObservable或类似的完成属性。转念一想封锁和乔恩斯基特著名的例子,以及如何打印出9(或10)一群倍,而不是数字的升序排列。所以我想,为什么不这样做:

Ok, i have a need to be able to keep track of value type objects which are properties on another object, which cannot be done without having those properties implement an IObservable interface or similar. Then i thought of closures and the famous example from Jon Skeet and how that prints out 9 (or 10) a bunch of times and not an ascending order of numbers. So i thought why not do this:

Class MyClass
{
    ...
    Func<MyValueType> variable;
    ...
    public void DoSomethingThatGetsCalledOften()
    {
        MyValueType blah = variable(); //error checking too not shown for brevity
        //use it
    }
    ...
}
... in some other consuming code ...
MyClass myClass = new MyClass();
myClass.variable = () => myOtherObject.MyOtherProperty;
//then myClass will get the current value of the variable whenever it needs it

显然,这将需要闭包的工作有一定的了解,但我的问题是这样的:这是一个好主意或肮脏的黑客和封闭系统的误用

编辑:由于一些人似乎误解了我想说的,这里是它演示了一个控制台程序:

Since some people seem to be misunderstanding what i'm trying to say, here's a console program which demonstrates it:

using System;
using System.Linq;

namespace Test
{
    class Program
    {
        public static void Main()
        {
            float myFloat = 5;
            Func<float> test = () => myFloat;
            Console.WriteLine(test());
            myFloat = 10;
            Console.WriteLine(test());
            Console.Read();
        }

    }
}

这将打印出 5 然后 10

推荐答案

在著名的公案你已经迷迷糊糊:的闭包是穷人的对象你正在使用动作&LT; T&GT; 来替代类型的属性的getter T 。这样的事会(略)少一个肮脏的把戏在一个更加动态的语言,因为它可以通过注射多数民众赞成装饰着你的日志功能的吸气剂来实现,但在C#中没有一个优雅的方式来monkeypatch别人的财产时,他们没有预料到。

You have stumbled upon the famous koan: Closures are a poor man's object. You are using Action<T> to substitute for a property getter of type T. Such a thing would be (slightly) less of a dirty trick in a more dynamic language, since it could be implemented by injecting a getter that’s decorated with your logging function, but in C# there isn’t an elegant way to monkeypatch someone’s property when they’re not expecting it.

这篇关于使用闭包跟踪变量:好主意或肮脏的把戏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆