这样做的更好方法? C#中的列表索引分配
Posted
技术标签:
【中文标题】这样做的更好方法? C#中的列表索引分配【英文标题】:Better way of doing this? List index assignment in C# 【发布时间】:2021-01-19 16:57:02 【问题描述】:所以,这段代码有效。但我觉得我在这里遗漏了一些基本的东西。为列表索引分配一个 int 来访问它们感觉不对。肯定有更好的方法来解决这个问题吗?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class ResourceHandler : MonoBehaviour
//Basic resources setup.
List<Resource> BasicResources = new List<Resource>();
// I want to avoid doing this, it seems dumb.
int Food = 0;
int Power = 1;
int Matter = 2;
int People = 3;
private void Start()
BasicResources.Add(new Resource("Food", 10));
BasicResources.Add(new Resource("Power", 10));
BasicResources.Add(new Resource("Matter", 100));
BasicResources.Add(new Resource("People", 5));
// This makes sense.
foreach (Resource resource in BasicResources)
Debug.Log(resource.Type + ", " + resource.Value);
//This works, but seems like a dumb way to do it.
BasicResources[Food].AddValue(10);
BasicResources[Power].AddMultiplier(0.25f);
【问题讨论】:
您最好使用Dictionary<TKey,TValue>
而不是List<T>
。 docs.microsoft.com/en-us/dotnet/api/…
如果你只有这四样东西,而且总是有这四样东西,只需创建一个结构,把这四样东西作为成员。
如果你为这 4 件事硬编码一个 int ,那么看起来你正在做出编译时决定,你不会有任何其他类型的东西,那么你如何让这些成为上课?
【参考方案1】:
您似乎需要一个枚举来说明您试图通过资源类型实现的目标?
...BasicResources.Add(new Resource(ResourceType.Food, 10));
然后通过枚举搜索您的资源 基本资源。首先 (x=> x.Type== ResourceType.Food).AddValue(10)
【讨论】:
【参考方案2】:public enum ResourceType Food, Power, Matter, People ;
public class Resource
public ResourceType Type get; private set;
public int Value get; private set;
public Resource(ResourceType type, int value)
Type = type;
Value = value;
public override string ToString()
return Type + ", " + Value;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class ResourceHandler : MonoBehaviour
//Basic resources setup.
List<Resource> BasicResources = new List<Resource>();
private void Start()
BasicResources.Add(new Resource(ResourceType.Food, 10));
BasicResources.Add(new Resource(ResourceType.Power, 10));
BasicResources.Add(new Resource(ResourceType.Matter, 100));
BasicResources.Add(new Resource(ResourceType.People, 5));
foreach (Resource resource in BasicResources)
Debug.Log(resource);
//This works, but seems like a dumb way to do it.
BasicResources[Food].AddValue(10);
BasicResources[Power].AddMultiplier(0.25f);
【讨论】:
以上是关于这样做的更好方法? C#中的列表索引分配的主要内容,如果未能解决你的问题,请参考以下文章