2 回答
TA贡献1900条经验 获得超5个赞
您可以通过重新初始化外观后面的实例来支付更少的成本,而不是支付反射成本。
public class AllThoseBooleans {
// expose values
public bool walkable => actual.walkable;
public bool current => actual.current;
public bool target => actual.target;
// real values defined here.
private class Actuals {
private bool walkable {get; set;}
private bool current {get; set;}
private bool target {get; set;}
}
private Actuals actual {get; set;} = new Actuals();
// reset all values to default by initialization
public void ResetAll() {
actual = new Actuals();
}
}
请注意:我没有运行它或测试访问修饰符;您可能需要调整这一点,但该理论认为:你们班布尔可以“拥有”存储可重新初始化太多太多比反射便宜。
TA贡献1891条经验 获得超3个赞
您可以这样做(这里的 Test 是具有所有布尔值的类):
Test test = new Test();
FieldInfo[] fields = typeof(Test).GetFields(); // Obtain all fields
foreach (var field in fields) // Loop through fields
{
string name = field.Name; // Get string name
object temp = field.GetValue(test); // Get value
if (temp is bool) // if it is a bool.
field.SetValue(test, false);
Console.WriteLine("name: {0} value: {1}",field.Name, field.GetValue(test));
}
输入类:
public class Test
{
public bool walkable = true;
public bool current = true;
public bool target = true;
public bool selectable = true;
public bool visited = true;
public string parent = null;
public int distance = 0;
}
输出:
name: walkable value: False
name: current value: False
name: target value: False
name: selectable value: False
name: visited value: False
name: parent value:
name: distance value: 0
- 2 回答
- 0 关注
- 165 浏览
添加回答
举报