好的,我需要能够跟踪值类型对象,这些对象是另一个对象的属性,如果这些属性不实现 IObservable 接口(interface)或类似接口(interface),就无法完成。然后我想到了闭包和 Jon Skeet 的著名例子,以及它如何多次打印出 9(或 10)而不是数字的升序。所以我想为什么不这样做:
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
显然,这需要对闭包的工作原理有所了解,但我的问题是:这是一个好主意还是一个肮脏的 hack 和对闭包系统的滥用?
编辑:由于有些人似乎误解了我的意思,这里有一个控制台程序可以演示它:
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
。
最佳答案
您偶然发现了著名的公案:Closures are a poor man's object.您正在使用 Action<T>
替代 T
类型的属性 getter .在更动态的语言中,这样的事情(稍微)不是一个肮脏的把戏,因为它可以通过注入(inject)一个用日志函数装饰的 getter 来实现,但是在 C# 中,没有一种优雅的方法来 monkeypatch 某人的属性(property),当他们没有预料到。
关于c# - 使用闭包跟踪变量 : Good idea or dirty trick?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1962539/