我有一个通用方法,传递的对象可能是单个对象或对象列表。示例:
public void MyGenericMethod<T>(T something, int? index)
{
// if it is a list how do I get to the object in the list?
}
有些情况下有人会通过一个列表。如果他们确实传递了一个对象列表,我将使用索引参数从列表中获取单个对象。我可以假设如果 index 不为 null 那么他们传入一个列表,但是我如何获得该值?我不能这样做:
object temp = something[index.Value];
重要的是要注意,我不能强制用户将单个对象传递到我的通用方法中。此外,我无法将其设为数组 (T[]) 并强制用户传入数组(或列表)。
最佳答案
您可以使用转换来获取 IList
.
IList list = something as IList;
if( list != null )
{
object temp = list[index.Value];
}
然而,使用一个专用于 IList
的泛型方法重载而不是一个庞大的泛型方法可能会更简单且类型更安全。
public void MyGenericMethod<T>(IList<T> something, int index)
{
var item = something[index];
// etc...
}
关于c# - 通用方法,如果它是一个列表,如何获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17574684/