Jue*_*gen 1 c# struct casting field
对不起这个新手问题,我对C#很新,它是语义.我有以下结构:
public struct MT5Command{
public MT5CommandType Type{ get; set;}
public AutoResetEvent ThreadWaitHandle { get; set; }
public object InParam { get; set; }
public object OutParam { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这段代码片段:
MT5Command Cmd = new MT5Command();
Cmd.Type = MT5CommandType.GetServerInformation;
Cmd.ThreadWaitHandle = waitHandle.Value;
attributes = new ServerAttributes();
Cmd.OutParam = attributes;
....
ServerAttributes SrvAttributes = new ServerAttributes();
Cmd.OutParam = (ServerAttributes)SrvAttributes;
Run Code Online (Sandbox Code Playgroud)
最后一行不编译:无法修改'command'的成员,因为它是'foreach迭代变量'如何将OutParam字段分配给另一个ServerAttributes结构?
这是外部for-each循环:
foreach (MT5Command Cmd in mCommandQueue.GetConsumingEnumerable())
{
...
}
Run Code Online (Sandbox Code Playgroud)
谢谢,Juergen
在这种情况下,你不能.你没有给出完整的片段,但我怀疑它是这样的:
foreach (MT5Command command in someCollection)
{
// Code as posted
}
Run Code Online (Sandbox Code Playgroud)
现在因为MT5Command是一个结构,你得到的是任何值的副本someCollection.无论如何,改变房产几乎肯定不会做你想要的.编译器通过将command变量设置为只读来保护您自己.你可以这样做:
MT5Command copy = command;
copy.OutParam = SrvAttributes;
Run Code Online (Sandbox Code Playgroud)
......但我强烈怀疑这不是你想要的.
作为一项规则,拥有像你提出的那样的可变结构是一个非常糟糕的主意 - 并且听起来不应该是首先应该是结构.
欲获得更多信息: