如何实例化MyCollection <t>类型的集合:IList <alert <t>&gt;?</alert <t> </t>

时间:2010-02-05 09:01:03

标签: c# generics collections c#-4.0

我有一个Alert <T>个对象。 假设我想获取MyObject类型的所有警报, 我会有一个类型的集合 MyCollection<MyObject> : IList<Alert<MyObject>>

我如何实现该列表的方法?

4 个答案:

答案 0 :(得分:1)

首先让我问你,为什么要建立自己的自定义系列?你真的需要它吗?如果是这样,您可能需要查看MSDN herehere,如果不使用框架中已有的任何通用集合类。

答案 1 :(得分:0)

我认为解决方案应该是某种动态构造函数。

答案 2 :(得分:0)

我想我找到了一个解决方案,但我还没有机会测试它。

public class Base
{

    private delegate Base ConstructorDelegate(int someParam);

    public class ClassReference
    {
        Type currentType = typeof(Base);

        public Base Create<U>() where U : Base
        {
            ConstructorInfo ci = currentType.GetConstructor(BindingFlags.Instance |
            BindingFlags.Public, null, Type.EmptyTypes, null);
            DynamicMethod dm = new DynamicMethod("CreateInstance", typeof(Base), Type.EmptyTypes, typeof(ClassReference));
            ILGenerator il = dm.GetILGenerator();
            il.Emit(OpCodes.Newobj, ci);
            il.Emit(OpCodes.Ret);
            ConstructorDelegate del = (ConstructorDelegate)dm.CreateDelegate(typeof(ConstructorDelegate));
            return del();
        }

        public Base Create<U>(int someParam) where U : Base
        {
            ConstructorInfo ci = currentType.GetConstructor(BindingFlags.Instance |
            BindingFlags.Public, null, new Type[] { typeof(int) }, null);
            DynamicMethod dm = new DynamicMethod("CreateInstance", typeof(Base), new Type[] {
            typeof(int) }, typeof(ClassReference));
            ILGenerator il = dm.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Newobj, ci);
            il.Emit(OpCodes.Ret);
            ConstructorDelegate del = (ConstructorDelegate)dm.CreateDelegate(typeof(ConstructorDelegate));
            return del(someParam);
        }

        private ClassReference(Type type)
        {
            currentType = type;
        }
        internal ClassReference() { }

        public static implicit operator ClassReference(Type input)
        {
            if (!typeof(Base).IsAssignableFrom(input))
                throw new Exception(String.Format("Type {0} must derive from {1}", input,
                typeof(Base)));
            return new ClassReference(input);
        }
    }


}

by Joanna Carter's c# version of Delphis Meta Class

答案 3 :(得分:0)

我想我找到了一个重要的内容:

 entityObject = objectContext.GetEntityByKey<T>(id);

从datacontext获取实体的通用方法