当我进入我的
Operation
类从外部,我使用反射设置它们的值数组字段。这是因为它更适合于自动化目的。
Calculate
),为了更好的可读性,我想按名称使用字段。字段的数量在派生自
操作
.
有没有比反射更快的方法?
public abstract class Operation
{
readonly FieldInfo[] inputFields;
public int InputCount {get {return inputFields.Length;}}
public Cacheable[] InputData
{
get
{
Cacheable[] result = new Cacheable[inputFields.Length];
for (int i=0; i<inputFields.Length; i++)
{
result[i] = (Cacheable)inputFields[i].GetValue(this);
}
return result;
}
set
{
for (int i=0; i<inputFields.Length; i++)
{
inputFields[i].SetValue(this, value[i]);
}
}
}
public Operation()
{
FieldInfo[] inputFields = GetType().GetFields();
}
public abstract void Calculate();
}
public class OperationA: Operation
{
public CacheableU SomeField;
public CacheableV AnotherField;
public override void Calculate()
{
DoSomething(SomeField, AnotherField);
}
}
public class OperationB: Operation
{
public CacheableU SomeField;
public CacheableV AnotherField;
public CacheableW YetAnotherField;
public override void Calculate()
{
DoSomethingElse(SomeField, AnotherField, YetAnotherField);
}
}
// ...
Cacheable[] inputsToA = new[]{c1, c2};
OperationA opa = new OperationA();
opa.InputData = inputsToA;
opa.Calculate();
Cacheable[] inputsToB = new[]{c3, c4, c5};
OperationB opb = new OperationB();
opb.InputData = inputsToB;
opb.Calculate();