简体   繁体   English

在C#中使用委托和Lambda处理struct的成员值

[英]Manipulate member values of struct with delegates and lambdas in C#

I'm learning lambdas and delegates in C# (and C# in general really), and I want to use these tools to manipulate member values of a struct. 我正在学习C#中的lambda和委托(实际上通常是C#),并且我想使用这些工具来操纵结构的成员值。 The struct is a Vector3, with x, y and z float values. 该结构是一个Vector3,具有x,y和z浮点值。 The values are even to 0.5f in my structs (could be 3.5f, 13.5f etc.) and I want to even them out further to whole numbers (3.0f, 13.0f etc.). 在我的结构中,该值甚至为0.5f(可以是3.5f,13.5f等),我想将它们进一步平整为整数(3.0f,13.0f等)。 What I have so far is: 到目前为止,我有:

delegate Vector3 PosDelegate (Vector3 pos);

private void SomeFunction(){
   Vector3 position = getPositionFromSomewhere();

   PosDelegate evenPos = p => p.x -= 0.5f;
   evenPos += p => p.y -= 0.5f;

   Vector3 newPosition = evenPos(position);
}

I know the problem is that the delegate parameter definition doesn't match the output of the lambda (Vector3 and float mismatch) and I get the errors: 我知道问题是委托参数定义与lambda的输出不匹配(Vector3和float不匹配),并且出现了以下错误:

Cannot implicitly convert type 'float' to 'Vector3' 无法将类型“ float”隐式转换为“ Vector3”

Cannot convert `lambda expression' to delegate type 'PosDelegate' because some of the return types in the block are not implicitly convertible to the delegate return type 无法将“ lambda表达式”转换为委托类型“ PosDelegate”,因为该块中的某些返回类型不能隐式转换为委托返回类型

but I'm not sure how to proceed. 但我不确定如何进行。 Explicitly casting doesn't work of course. 明确地进行投射当然是行不通的。 Changing the lambda to something like 将lambda更改为类似

evenPos = p => (p.x, p.y, p.z) = (p.x - 0.5f, p.y -0.5f, 0.0f);

yields the same errors. 产生相同的错误。

Any tips are greatly appreciated. 任何提示,不胜感激。

Your delegate has to return a Vector3 , not void . 您的代表必须返回Vector3 ,而不是void Thus simply write the following: 因此,只需编写以下内容:

delegate Vector3 PosDelegate (Vector3 pos);

private void SomeFunction()
{
   Vector3 position = getPositionFromSomewhere();

   PosDelegate evenPos = p => new Vector { x = p.x - 0.5f, y = p.y - 0.5f };
   evenPos(position);
}

Be aware that struct are value-types. 请注意, struct是值类型。 Thus whatever you get from getPositionFromSomewhere will completely be copied into a new instance of Vector3 and after calling the delegate copied a second time. 因此,从getPositionFromSomewhere获得的任何内容都将完全复制到Vector3的新实例中,并在调用委托后第二次复制。

Making your delegate to not return anything ( void ) won´t work by the way, as the instance of Vector3 is copied when passed to the delegate. 顺便说一句,使您的委托人不返回任何内容( void )将不起作用,因为将Vector3的实例传递给委托人时会对其进行复制。 Thus every change you´re making within that delegate won´t be reflected outside it. 因此,您该代表中所做的每项更改都不会外部反映出来。 See also why mutable structs are evil 另请参阅为什么可变结构是邪恶的

您可能只是在委托中返回Vector3的新实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM