我上了这个课:
public class City
{
public string city;
public float residence;
public float industry;
public float trade;
public float total;
}
我想使用foreach循环访问行:
List<City> cities = new List<City>();
string[] rows = {"city", "residence", "industry", "trade", "total"};
foreach(string x in rows)
{
Debug.Log(cities[5].x); // this doesn't work
}
cities[5].residence
或cities[5].total
可以工作,但我不想直接写。
我想引用residence
之类的industry
或cities[3].x
,如何使它以这种方式工作?
答案 0 :(得分:1)
由于您使用的是面向对象的程序C#,因此我鼓励您改善代码的封装:思考行为而不是数据。
这意味着可以通过以下方式将City
改进为实现该目标:
public sealed class City
{
private readonly string city;
private readonly float residence;
private readonly float industry;
private readonly float trade;
private readonly float total;
public City(string city, float residence, float industry, float trade, float total)
{
this.city = city;
this.residence = residence;
this.industry = industry;
this.trade = trade;
this.total = total;
}
public IEnumerable<string> YieldProperties()
{
yield return city;
yield return residence.ToString("R");
yield return industry.ToString("R");
yield return trade.ToString("R");
yield return total.ToString("R");
}
}
使用情况变为
List<City> cities = new List<City>();
foreach(string p in cities[5].YieldProperties())
{
Debug.Log(p);
}
那我做了什么改变?
sealed
和readonly
使该类不可变(这是可维护性的一种好习惯)rows
,这非常危险:如果忘记更新City
的内容,则在rows
中重命名字段将破坏代码