索引器
struct Point
{
double x;
double y;
double z;
public double this[int x]
{
get
{
switch (x)
{
case 0: return x;
case 1: return y;
case 2: return z;
default: throw new ArgumentOutOfRangeException();
}
}
}
}
/*
这样就可以使用p[0],p[1],p[2]来访问p.x, p.y, p.z了(p = new Point())
*/
枚举器
struct Point
{
double x;
double y;
double z;
public IEnumerator<double> GetEnumerator()
{
return MyIE();
}
public IEnumerator<double> MyIE()
{
yield return x;
yield return y;
yield return z;
}
}
需要注意的是枚举值是只读的,所以没有办法对数据进行修改
如果是要对多个结构枚举,可以使用using语句来实现,具体参考using-foreach-to-iterate-simultaneously-through-multiple-lists
反射机制
public User(string name, int year, bool gender)
{
this.name = name;
this.year = year;
this.gender = gender;
}
User user = new User("miao", 23, true);
foreach (FieldInfo field in typeof(User).GetFields(BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public))
{
Debug.LogFormat("{0} = {1}", field.Name, field.GetValue(user));
}
参考StackOverflow
反射的耗时大概是直接放问的两三倍,所以还是尽量直接访问吧~