好的,我需要能够跟踪值类型对象,这些对象是另一个对象的属性,如果不让这些属性实现 IObservable 接口或类似接口,就无法做到这一点。然后我想到了闭包和 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
显然,这需要对闭包的工作原理有所了解,但我的问题是:这是一个好主意还是一个肮脏的黑客和对闭包系统的滥用?
编辑:由于有些人似乎误解了我想说的话,这里有一个控制台程序来演示它:
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
。