Sorry for this newbie question, I'm very new to C# and it's semantics. I have the following struct:
public struct MT5Command{
public MT5CommandType Type{ get; set;}
public AutoResetEvent ThreadWaitHandle { get; set; }
public object InParam { get; set; }
public object OutParam { get; set; }
}
And this code snippet:
MT5Command Cmd = new MT5Command();
Cmd.Type = MT5CommandType.GetServerInformation;
Cmd.ThreadWaitHandle = waitHandle.Value;
attributes = new ServerAttributes();
Cmd.OutParam = attributes;
....
ServerAttributes SrvAttributes = new ServerAttributes();
Cmd.OutParam = (ServerAt开发者_如何学Pythontributes)SrvAttributes;
The last line does not compile: Cannot modify members of 'command' because it is a 'foreach iteration variable' How is it possible to assign the OutParam field to another ServerAttributes struct?
This is the outer for-each loop:
foreach (MT5Command Cmd in mCommandQueue.GetConsumingEnumerable())
{
...
}
Thanks, Juergen
You can't, in this case. You haven't given the full snippet, but I suspect it's something like this:
foreach (MT5Command command in someCollection)
{
// Code as posted
}
Now because MT5Command
is a struct, you're getting a copy of whatever value is in someCollection
. Changing the property almost certainly wouldn't do what you wanted it to anyway. The compiler is protecting you from yourself, by making the command
variable read-only. You could do this:
MT5Command copy = command;
copy.OutParam = SrvAttributes;
... but I strongly suspect that's not what you want.
As a rule, it's a really bad idea to have mutable structs like the one you've come up with - and it doesn't sound like that should be a struct in the first place.
For more information:
- My article on value types and reference types
- MSDN guidelines on when it's appropriate to create a struct
精彩评论