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

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

问题描述

好吧,我需要能够跟踪作为另一个对象的属性的值类型对象,这些属性不能实现IObservable接口或类似的接口。然后我想到了闭包和Jon Skeet的着名例子,以及如何打印出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

这将需要一些理解闭包如何工作,但我的问题是这样:这是一个好主意或坏的黑客和滥用闭合系统?

Obviously this would require some understanding of how closures work, but my question is this: is this a good idea or a dirty hack and a misuse of the closure system?

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

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

推荐答案

你偶然发现了着名的koan:关闭是一个穷人的对象。你正在使用 Action 来代替 / code>。这样的事情会(更少)在一个更动态的语言,一个脏的伎俩,因为它可以通过注入一个getter,用你的日志功能装饰,但在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天全站免登陆