You are over-thinking this.
In this method, you are creating one instance of MyCounter
, that increments every time you invoke the delegate.
static void Example01(){
var myCounterLocalInstance = new MyCounter();
Action<string> lambdaFunction = (args) => IncrementAndPrint(args, myCounterLocalInstance);
lambdaFunction("cat");
lambdaFunction("cat");
lambdaFunction("cat");
lambdaFunction("cat");
}
In this method you are creating a new instance MyCounter
every time you invoke the delegate, its count will always be 0!
static void Example02(){
Action<string> lambdaFunction = (args) => IncrementAndPrint(args, new MyCounter());
lambdaFunction("cat");
lambdaFunction("cat");
lambdaFunction("cat");
lambdaFunction("cat");
}
You would get the same results if you just called the IncrementAndPrint
statically:
static void Example01(){
var myCounterLocalInstance = new MyCounter();
IncrementAndPrint("cat",myCounterLocalInstance);
IncrementAndPrint("cat",myCounterLocalInstance);
IncrementAndPrint("cat",myCounterLocalInstance);
IncrementAndPrint("cat",myCounterLocalInstance);
}
static void Example02(){
IncrementAndPrint("cat", new MyCounter());
IncrementAndPrint("cat", new MyCounter());
IncrementAndPrint("cat", new MyCounter());
IncrementAndPrint("cat", new MyCounter());
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…