创建< T>的列表;从基类 [英] Create a List of <T> from a base class

查看:77
本文介绍了创建< T>的列表;从基类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为SCO的基类,许多类都继承自该基类.我最初只是想对集合进行排序,但是根据一些建议,听起来我可以用一种方法实例化集合并对其进行排序.

I have a base class called SCO that a number of classes inherit from. I initially just wanted to sort the collection, but based off of some recommendations, it sounds like I can instantiate and sort the collection in one method.

我有一个所有基类都继承的构造函数:

I have this constructor that all base classes inherit:

public SCO(SPListItem item, List<Vote> votes)
{
    UpVotes = voteMeta.UpVotes;
    DownVotes = voteMeta.DownVotes;
    VoteTotal = UpVotes - DownVotes;
    HotScore = Calculation.HotScore(Convert.ToInt32(UpVotes), Convert.ToInt32(DownVotes), Convert.ToDateTime(item["Created"]));
}

这就是我被困住的地方.我无法实例化<T>.

This is where I get stuck. I cannot instantiate <T>.

public static List<T> SortedCollection<T>(SPListItemCollection items, ListSortType sortType, List<Vote> votes) where T : SCO
{
    var returnlist = new List<T>();
    for (int i = 0; i < items.Count; i++) { returnlist.Add(new T(items[i], votes)); }
    switch (sortType)
    {
        // Sort List based on passed ENUM
    }
    return returnlist;
}

如果我可以用一种方法完成所有这些操作,则可以避免进行一些昂贵的投射和装箱操作.

If I can do all of this in one method, I avoid some costly casting AND boxing.

推荐答案

泛型中唯一允许的约束是new(),它仅在存在不带任何参数的构造函数时才起作用.

The only constraint allowable in generics is new(), which will only work if there is a constructor which does not take any parameters.

我有一个所有基类都继承的构造函数:

I have this constructor that all base classes inherit:

问题在于,这不是可执行的.子类可以(并且应该)自由定义自己的构造函数,只要它们链接到该构造函数即可.子类可以自由使用实例化该类所需的任何构造机制.

The problem is that this isn't enforceable. Sub classes are (and should be) free to define their own constructors, as long as they chain to this constructor. A sub class is free to use whatever construction mechanism required to instantiate that class.

您可以通过反射和 Activator.CreateInstance 解决此问题.允许您使用参数构造对象.但是,这相当丑陋"(尽管考虑到使用

You could work around this via reflection and Activator.CreateInstance, which will allow you to construct the object with parameters. However, this is fairly "ugly" (though, not that ugly considering that using the new() constraint still calls Activator.CreateInstance):

Type genericType = typeof(T);
for (int i = 0; i < items.Count; i++) 
{ 
     returnlist.Add((T)Activator.CreateInstance(genericType, new object[] {items[i], votes})); 
}

这篇关于创建&lt; T&gt;的列表;从基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆