1

我试图概括一个应该填充 List<> 或 Dictionary<> 的函数失败了。首先以下不编译:

T foo<T>() where T : ICollection, new()
{
  T t = new T();

  t.Add(1, 1);

  return t;
}

错误 1“T”不包含“添加”的定义,并且找不到接受“T”类型的第一个参数的扩展方法“添加”(您是否缺少 using 指令或程序集引用?)

其次,假设如果这会编译“添加”如何被概括?

t.Add(1, 1) // for dictionaries
and t.Add(1) // for Lists

如果有可能,那就太好了

4

3 回答 3

0

也许像下面这样的扩展方法

    public static void AddToCollection(this ICollection col, object value)
    {
        if (col is IDictionary)
        {
            ((IDictionary)col).Add(value, value);
        }
        else if(col is IList)
        {
            ((IList)col).Add(value);
        }
    }

然后替换

t.Add(1, 1);

t.AddToCollection(1);
于 2013-10-25T14:15:47.457 回答
0

我想出了这个,不是最优雅的解决方案,不确定我是否会在生产中采用它。它从使用 Func<> 传入的查询中读取 SQL 服务器表,并且作为参数传入的 Action 对象用于将对象添加到集合中。

public C Read<C, T>(Func<SqlConnection, SqlDataReader> func, Action<C, T> a)
    where C : ICollection, new()
    where T : EntityBase, new()
{
    C objects = new C();

    using (SqlConnection connection = GetConnection())
    {
        using (SqlDataReader reader = func(connection))
        {
            while (reader.Read())
            {
                T obj = new T();
                obj.PopulateFromReader(reader);
                a(objects, obj);
            }
        }
    }

    return objects;
}

像这样调用:

       Dictionary<Guid, DeliveryMoment> dic = _dalBO.Read<Dictionary<Guid, DeliveryMoment>, DeliveryMoment>(connection => { return CmdFactory.ReadDeliveryMoments(connection); }, (d, o) => { d.Add(o.DeliveryMomentId, o); });

你怎么看?太阴暗或可以接受?

于 2013-10-25T13:38:04.007 回答
0
static T Temp<T>(params object[] obj) where T:ICollection, new ()
    {
        T s = new T();
        //TODO: validation for input values
        if (s is IDictionary)
        {
            ((IDictionary) s).Add(obj[0], obj[1]);
        }
        else if (s is IList)
        {
            ((IList)s).Add(obj[0]);
        }

        return s;
    }
于 2013-10-25T13:50:50.607 回答