c# - 在 Unity C# 中编辑结构值
问题描述
我创建了一个名为 Teams 的字典,并使用一个结构来保存一个整数、一个字符串和一个布尔值。
因此,如果有人加入红队,则 bool 将为 false,以防止其他玩家加入同一队。
我试图将布尔值设置为 false,但它失败了。
public Dictionary <int , myCustomType> Teams = new Dictionary<int,myCustomType>();
private ExitGames.Client.Photon.Hashtable m_PlayerCustomPropeties = new ExitGames.Client.Photon.Hashtable();
private void addTeams()
{
myCustomType t=new myCustomType();
t.name="Yellow";
t.flag= true;
Teams.Add(1,t);
t.name="Red";
t.flag= true;
Teams.Add(2,t);
t.name="Blue";
t.flag= true;
Teams.Add(3,t);
t.name="Green";
t.flag= true;
Teams.Add(4,t);
Debug.Log("Teams created.");
}
public void getPlayers()
{
Debug.Log(Teams[1].flag);
Teams[1] = new myCustomType { flag = false };
}
解决方案
您的类型定义为:
public struct myCustomType
{
public string name;
public bool flag;
}
并且Teams
是一个Dictionary<int, myCustomType>
. 当您尝试以下操作时:
Teams[1].flag = false;
它失败了,因为Teams[1]
它只是一个值(Dictionary<,>
索引器 getter 的返回值)。
您的类型myCustomType
是可变结构。该结构是按值返回的,因此尝试修改返回的值的副本是没有意义的。
你会需要:
var mct = Teams[1]; // 'mct' is a copy of the value from the 'Dictionary<,>'.
mct.flag = false; // You modify the copy which is allowed because 'mct' is a variable.
Teams[1] = mct; // You overwrite the old value with 'mct'.
有些人认为可变结构是邪恶的。
推荐阅读
- python-3.x - 如何在 matplotlib 的 3d 曲面中到达实体曲面?
- google-sheets - 用于计算列中唯一值出现次数的 Google 表格公式
- django - Django:对象未显示在索引页面上
- docker - 从同一个 docker compose 中的 docker 容器拒绝连接
- python - 如何将 Flask 应用程序连接到在 Docker 中运行的 SQLite DB?
- wpf - 将网格大小设置为窗口大小
- amazon-web-services - AWS CloudFormation:如何在 AWS Pipeline 中使用 Github Enterprise 作为源
- javascript - 如何减少重复来源?
- c++ - 使用 thread::detach 时如何检查线程是否已完成
- go - Go protobuf 中单独消息和服务定义的最佳实践?