通用列表和扩展方法的问题(C#3.0)

时间:2010-04-28 06:48:27

标签: c#-3.0

我有一个问题。我正在为Collection创建一个扩展类,它是通用的......比如

public static class ListExtensions
    {

        public static ICollection<T> Search<T>(this ICollection<T> collection, string stringToSearch)
        {
            ICollection<T> t1=null;           

            foreach (T t in collection)
            {
                Type k = t.GetType();
                PropertyInfo pi = k.GetProperty("Name");
                if (pi.GetValue(t,null).Equals(stringToSearch))
                {
                    t1.Add(t);
                }
            }
            return t1;
        }
    }

但我无法将项目添加到t1,因为它被声明为null。 错误:对象引用未设置为对象的实例。

我正在调用类似

的方法
List<TestClass> listTC = new List<TestClass>();

            listTC.Add(new TestClass { Name = "Ishu", Age = 21 });
            listTC.Add(new TestClass { Name = "Vivek", Age = 40 });
            listTC.Add(new TestClass { Name = "some one else", Age = 12 });
            listTC.Search("Ishu");

测试类是

public class TestClass
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

使用:(C#3.0)&amp;框架 - 3.5 感谢

2 个答案:

答案 0 :(得分:1)

想要使用哪种收藏品?你必须有一个实际的集合来添加你的结果。 List<T>可能是最简单的建议。只需更改方法的第一行:

ICollection<T> t1 = new List<T>();

编辑:虽然这是对代码的最简单的更改,但您应该根据Thomas的答案考虑使用迭代器块。

答案 1 :(得分:1)

由于您可能不希望在执行Search后操纵(添加,删除,...)搜索结果,因此最好返回IEnumerable<T>而不是ICollection<T> }。此外,C#还有一个特殊的语法:yield

public static class ListExtensions
{
    public static IEnumerable<T> Search<T>(this ICollection<T> collection, string stringToSearch)
    {
        foreach (T t in collection)
        {
            Type k = t.GetType();
            PropertyInfo pi = k.GetProperty("Name");
            if (pi.GetValue(t,null).Equals(stringToSearch))
            {
                yield return t;
            }
        }
    }
}