-1
private void Call()
{
    List<int> numbers= Get<List<int>>();
    MessageBox.Show("Numbers amount " + numbers.Count);
}

private T Get<T>() 
{
    T list = Activator.CreateInstance<T>();
    int a = 1;
    //HOW TO ADD "A" TO THE T-object [which is a list...]?
    return list;
}

Is it possible to let "T" be a List? I mean, it is possible (it compiles), but how do you add an object to these kind of lists?

4

3 回答 3

1

我相信你想要:

private static T Get<T>() where T : IList
{
    T list = Activator.CreateInstance<T>(); 
    int a = 1;
    (list as IList).Add(a);
    return list;
}
于 2014-11-24T16:19:32.303 回答
0

如果您T总是应该具有添加整数的能力,那么您本质上说的是它实现了ICollection<int>. 添加ICollection<int>为类型约束后,您应该可以很容易地做到这一点:

private T Get<T>() where T: ICollection<int>, new
{
    T coll = new T();
    int a = 1;

    coll.Add(a);
    return coll;
}

评论中所述,您也可以避免,Activator.CreateInstance因为您不需要任何构造函数参数。

现在您可以使用:

var myList = Get<List<int>>();
Console.WriteLine(myList.Count); // Should be 1

这是一个演示:http: //ideone.com/0pjFoJ

于 2014-11-24T16:18:30.780 回答
0

What Asad said, but if you want a generic method to get a list, I would propose calling it GetList and doing the following (notice that adding is done in a lambda so you can add whatever you want or provide a function to do so):

private void Call()
        {
            List<int> numbers = GetList<int>(l =>
            {
                l.Add(1);
                l.Add(2);
                //etc
            });
            MessageBox.Show("Numbers amount " + numbers.Count);
        }

        private List<T> GetList<T>(Action<List<T>> initList)
        {
            List<T> list = Activator.CreateInstance<List<T>>();
            initList(list);
            return list;
        }
于 2014-11-24T16:39:18.423 回答