複数パラメーターのコンストラクターと静的な並べ替えられたコレクションを持つインターフェイスを実装するクラスがあります。このクラスは、多くの継承クラスを持つ基本クラスです。
internal class SCO : IVotable
{
public SCO(SPListItem item, List<Vote> votes)
{
//Initialize Object
}
public static List<T> SortedCollection<T>(SPListItemCollection items, ListSortType sortType, List<Vote> votes) where T : IVotable
{
var returnlist = new List<T>();
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;
}
}
これにより、任意の子クラスで次のことができます。
List<ChildClass> sortedClassList = ChildClass.SortedCollection<ChildClass>(listItems, sortType, votes);
現在 Activator.CreateInstance に依存していることは心配です。Emit IL を直接使用するよりも約 100 倍遅いからです。Emit IL に関するいくつかの記事を読んでいますが、このソリューションは素晴らしいと思います。
しかし、私はそれを機能させることができないようです。インスタンス化しようとすると、ILGenerator gen =
「静的コンテキストで非静的フィールド 'メソッド' にアクセスできません」と表示されます。
私のクラスもコンストラクターも静的ではありません。以下に示す静的リストはまだ Emit とやり取りしていません。どうすればこれを機能させることができますか?
これまでのコード:
internal class SCO : IVotable
{
//Properties emittied
static ConstructorInfo ctor = typeof(SCO).GetConstructors()[1];
delegate SCO SCOCtor(SPListItem item, List<Vote> votes);
static SCOCtor SCOCtorDelegate;
DynamicMethod method = new DynamicMethod("CreateInstance", typeof (SCO),
new Type[] {typeof (SPListItem), typeof (List<Vote>)});
ILGenerator gen = method.GetILGenerator(); //Error here
//"Cannot access non-static field 'method' in static context"
private static SCO CreateInstance(SPListItem item, List<Vote> votes)
{
return SCOCtorDelegate(item, votes);
}
}
参考ブログ: http://ayende.com/blog/3167/creating-objects-perf-implications