【发布时间】:2011-11-30 09:19:44
【问题描述】:
我如何传递一个列表,该列表是一个 DerivedObjects 列表,其中该方法需要一个 BaseObjects 列表。我正在转换列表.ToList<BaseClass>() 并想知道是否有更好的方法。我的第二个问题是语法不正确。我正在尝试通过引用传递列表,但出现错误:'ref' argument is not classified as a variable
如何解决这两个问题?谢谢。
public class BaseClass { }
public class DerivedClass : BaseClass { }
class Program
{
static void Main(string[] args)
{
List<DerivedClass> myDerivedList = new List<DerivedClass>();
PassList(ref myDerivedList.ToList<BaseClass>());
// SYNTAX ERROR ABOVE IS - 'ref' argument is not classified as a variable
Console.WriteLine(myDerivedList.Count);
}
public static void PassList(ref List<BaseClass> myList)
{
myList.Add(new DerivedClass());
Console.WriteLine(myList.Count);
}
}
已解决:
类似的方法解决了我的问题。
public static void PassList<T>(ref List<T> myList) where T : BaseClass
{
if (myList == null) myList = new List<T>();
// sorry, i know i left this out of the above example.
var x = Activator.CreateInstance(typeof(T), new object[] {}) as T;
myList.Add(x);
Console.WriteLine(myList.Count);
}
感谢所有帮助解决这个问题和其他 SO 问题的人。
【问题讨论】:
-
在这种情况下为什么需要
ref? -
ref 是必需的,否则添加的项目仍然与该方法一起装箱。 (希望我得到了正确的条款)。
-
List是一个引用类型类。方法中添加的项目将被添加到同一个实例中。 -
@Valamas:不,你不明白
ref是如何工作的(或者可能是引用类型是如何工作的)。按照我的答案中的链接并非常仔细地阅读它。 -
我以前没有见过“where T : BaseClass”语法,这很有用。感谢您发布已解决的代码。
标签: c# derived-class generic-list ref