我有一个接受 object 的方法.我知道的这个对象是 List<T>然而,当 T 被传递到方法中时,基类的子级之间的 T 在任何时候都可能不同。
所以如果我的基类是 MonthType , 我有 child 叫 BlockMonthType和 AreaMonthType传入的对象可以是 List<BlockMonthType> or List<AreaMonthType> 中的任何一个.
我希望能够向这个对象添加项目,但是当我转换它时,它似乎制作了一个副本并且原始对象没有更新。
我这样做是为了转换:
var objectList = ((IEnumerable<MonthType>)graphObject.Source.Object).ToList();
现在我想创建一个新项目并将其添加到列表中
// where ObjectType is a Type variable containing BlockMonthType
var newObject = (BlockMonthType)Activator.CreateInstance(graphObject.Source.ObjectType);
objectList.Add(newObject);
// and carry on the world is good
只要 objectList 添加了一个 newObject,这就有效。然而,原始变量没有更新,所以当我离开方法时,它又回到了它的原始状态。我知道该对象在传入时是一个 List<>,因为我可以在调试器中看到它。
无论如何我可以完成这个吗?
这是我正在使用的方法的简化版本。
public TraverseGraphResult Write(ObjectGraph graphObject)
{
var objectList = ((IEnumerable<MonthType>)graphObject.Source.Object).ToList();
var newObject = (MonthType)Activator.CreateInstance(rule.ObjectType);
newObject.Month = rule.Month;
objectList.Add(newObject);
// Other stuff as well is done but that's the crux of it
}
希望这能给它更多的上下文。该方法用于尝试导航具有许多类类型的大型对象树。我正在尝试添加一个新的类类型处理程序,它将处理从列表中添加和删除项目。
// This is being used in a recursive method to loop down a object's property tree
// .. more code here
// where properties is a List<PropertyInfo>
foreach (var pInfo in properties)
{
if (IsList(pInfo.PropertyType))
{
var enumerable = (IEnumerable)pInfo.GetValue(currentObjectGraph.Source.Object, null);
var sourceEnumerator = enumerable.GetEnumerator();
var graph = new ObjectGraph(enumerable, pInfo.Name);
// this part is made up but essentially the code looks up a list of objects that can deal with this
// particular one and returns it. We then call the write method on that object
var something = GetInterfaceHandlerForObject(enumerable);
something.Write(graph);
}
}
请您参考如下方法:
你应该使你的方法通用:
public void MyMethod<T>(List<T> objectList) where T:class, new()
{
objectList.Add(new T());
...
}
当您使用泛型时,很少需要转换。此外,您的 ToList() 导致创建列表的新副本。
这种方法的一个缺点是 T需要有一个空的构造函数。如果您需要构造一个带有参数的对象,您可以改为传入 Func<T>。 .然后您可以调用它传递一个 lambda 表达式,例如:(x) => new BlockMonthType(someParameter, orAnother) .
