当名称未知时,如何调用unknowList.AddRange(elements)
?
我有以下代码,但addMethod
始终为空。有什么原因吗?
public class Tree : Harvestable
{
}
public class JobManager
{
List<Tree> treeSelections = new List<Tree>();
public void OnMarkHarvestableSignal(List<Harvestable> selections)
{
string fieldName = selections[0].GetType()
.ToString()
.ToLower() + "Selections";
FieldInfo field = this.GetType()
.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
if (field is null)
throw new Exception($"Field {fieldName} not found");
MethodInfo addMethod = field.GetType()
.GetMethod("AddRange");
addMethod.Invoke(field, new object[] {selections});
}
}
您可能需要Harvestable
实例来标识自己:
public abstract class Harvestable // or however it’s actually defined
{
public abstract Category Category { get; }
}
其中,Category
可以是具有每个类的条目的enum
,或者object
、string
,或者一些自定义的类似符号的类型。
然后JobManager
维护一个列表字典:
public class JobManager
{
Dictionary<Category, List<Harvestable>> CategorySelections
= new Dictionary<Category, List<Harvestable>>();
public void OnMarkHarvestableSignal(List<Harvestable> selections)
{
CategorySelections[selections[0].Category].AddRange(selections);
}
}