多播委托总是执行最后一个操作
所以我有以下代码:
namespace ConsoleApplication1
{
public delegate int Transformer(int x);
class Test
{
public static void Transform(int[] values, Transformer t)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = t(values[i]);
}
}
static int Square(int x)
{
return x * x;
}
static int Minus(int x)
{
return x - 1;
}
static void Main()
{
int[] values = { 1, 2, 3 };
Transformer t = Test.Minus;
t += Test.Square;
Test.Transform(values, t);
foreach (int i in values)
{
Console.Write(i + " ");
}
}
}
}
为什么它总是只对数组执行最后一个操作(在我的例子中是 Square )。我应该改变什么才能同时实现 Minus 和 Square ?
So I have the following the code:
namespace ConsoleApplication1
{
public delegate int Transformer(int x);
class Test
{
public static void Transform(int[] values, Transformer t)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = t(values[i]);
}
}
static int Square(int x)
{
return x * x;
}
static int Minus(int x)
{
return x - 1;
}
static void Main()
{
int[] values = { 1, 2, 3 };
Transformer t = Test.Minus;
t += Test.Square;
Test.Transform(values, t);
foreach (int i in values)
{
Console.Write(i + " ");
}
}
}
}
Why is it always does only the last operation to the array(Square in my case). What should I need to change so it will do both Minus and Square ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
多播委托始终返回链中最后一个委托的值。由于您不修改 Test.Minus 和 Test.Square 中的值,而是返回新值,因此仅应用后者。解决这个问题最简单的方法是让你的变压器通过引用获取值并修改它们。例如:
Multicast delegates always return the value of the last delegate in chain. Since you don't modify values in Test.Minus and Test.Square, but return new values, only latter is applied. The simplest way to fix this would to make your transformers take values by reference and modify them. e.g:
因为结果并未链接到所有委托,
所以代码就相当于
更改代码以更改变量。
更好的解决方案是使用 linq 聚合,因为您可以在不影响源的情况下转换解决方案。
然后你可以只调用
或
在此调用值之后!=结果,因此源不变
Because the result is not chained through all the delegates
the code becomes the equivalent of
change the code to alter the variable in place.
A far better solution would be to use a linq agregate because you could transform the solution without affecting the source.
Then you can just call
or
After this call values!=result so source is unchanged