使用Emit IL和内部类?

Wes*_*ley 1 c# reflection performance reflection.emit instantiation

我有一个基类,它有一个嵌入式List,所有子类都可以使用它来返回一个已排序的集合.

我一直在使用Activator.CreateInstance(),但与简单的new()函数相比,这是比较慢的TERRBILY.

我找到了一种使用Emit IL的方法,几乎​​和new()一样快,但如果我的类不公开,我会收到MethodAccessException错误.这似乎很常见.

有没有解决的办法?

这里生成类的代码:http: //codeblocks.codeplex.com/wikipage?title = FastActivator%20Sample

代码与上面的代码一起使用:

public static List<T> SortedCollection<T>(SPListItemCollection items, ListSortType sortType, List<Vote> votes) where T : IVotable
{
    var returnlist = new List<T>();  
    var functionCreator = FastActivator.GenerateFunc<Func<SPListItem, List<Vote>, T>>();
    for (int i = 0; i < items.Count; i++) { returnlist.Add(functionCreator(items[i], votes)); }

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

    switch (sortType)
    {
        case ListSortType.Hot:
            returnlist.Sort((p1, p2) => p2.HotScore.CompareTo(p1.HotScore));
            break;
        case ListSortType.Top:
            returnlist.Sort((p1, p2) => p2.VoteTotal.CompareTo(p1.VoteTotal));
            break;
        case ListSortType.Recent:
            returnlist.Sort((p1, p2) => p2.CreatedDate.CompareTo(p1.CreatedDate));
            break;
        }
        return returnlist;
    }

    //Usage
    //Post : BaseClass which has above method
    return Post.SortedCollection<Post>(listItems,sortType,votes);
Run Code Online (Sandbox Code Playgroud)

Joa*_*son 5

您可以使用DynamicMethod构造函数(String,Type,Type [],Type)方法生成与要访问的成员的类关联的方法.

生成的方法将具有对与其关联的类型中的所有成员的完全访问权限,以及该类在其模块中可以访问的所有内部方法和成员.