我可以创建List <class <t>&gt;?</class <t>

时间:2011-06-05 10:03:52

标签: c# .net generics

我有一个班级

public class Setting<T>
{
    public string name { get; set; }

    public T value { get; set; }
}

现在我想创建一个IList<Setting<T>>,但其中包含Setting<T>个不同类型的T,我想要e.G.

List<Setting<T>> settingsList;
settingsList.Add(new Setting<int>());
settingsList.Add(new Setting<string>()); 

我已经尝试IList<Setting<T>>但这似乎不可能,因为编译器找不到类型T

我知道我可以使用对象,但我希望它是强类型的。所以我的问题是,是否有可能让这个工作。

5 个答案:

答案 0 :(得分:10)

默认情况下,通用类型在具体定义中没有通用类型或接口。

让您的Setting<T>类实现一个接口(或从一个公共类派生)并创建该接口(或类)的列表。

public interface ISetting { }

public class Setting<T> : ISetting
{
    // ...
}

// example usage:
IList<ISetting> list = new List<ISetting>
{
    new Setting<int> { name = "foo", value = 2 },
    new Setting<string> { name = "bar", value "baz" },
};

答案 1 :(得分:0)

您必须为放入列表的所有类类型使用共同的祖先类。如果它应该是任意类型,则必须使用object作为T

答案 2 :(得分:0)

您只能在班级内使用T

class Setting<T>
{
    // T is defined here
}

不在外面。在外面你需要指定具体的类型:

Settings<string> stringSettings = new Settings<string>();

List<Settings<string>> list = new List<Settings<string>>();
list.Add(stringSettings);

答案 3 :(得分:0)

你可以用反射来做到这一点 我为另一个问题编写了这样的代码,但你可以使用这个

public abstract class GenericAccess
{
    public static IList<T> GetObjectListFromArray<T>(T item)
    {
        var r = new List<T>();
        var obj = typeof(T).Assembly.CreateInstance(typeof(T).FullName);
        var p = obj.GetType().GetProperty("Id", System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
        if (p != null)
        {
            p.SetValue(obj, item, null);
            var m = r.GetType().GetMethod("Add");
            m.Invoke(r, new object[] { obj });
        }
        return r;
    }
}

并像这样称呼它

    IList<int> r = GenericAccess.GetObjectListFromArray<int>(1);

答案 4 :(得分:-1)

/// <summary>
/// 消息回调委托
/// </summary>
/// <typeparam name="T">TClass</typeparam>
/// <param name="result">返回实体</param>
/// <param name="args">内容包</param>
public delegate void CallbackHandler<in T>(T result, BasicDeliverEventArgs args);

/// <summary>
/// 注册监听程序接口
/// </summary>
public interface IRegistration
{
    /// <summary>
    /// 路由名称
    /// </summary>
    string ExchangeName { get; }

    /// <summary>
    /// 路由Key
    /// </summary>
    string RouteKey { get; }

    /// <summary>
    /// 回调操作
    /// </summary>
    /// <param name="args"></param>
    void Call(BasicDeliverEventArgs args);
}

/// <summary>
/// 注册监听程序
/// </summary>
/// <typeparam name="T"></typeparam>
public class Registration<T> : IRegistration where T : class
{
    /// <summary>
    /// 路由名称
    /// </summary>
    public string ExchangeName { get; set; }

    /// <summary>
    /// 路由Key
    /// </summary>
    public string RouteKey { get; set; }

    /// <summary>
    /// 消息处理器委托
    /// </summary>
    public CallbackHandler<T> Handler { get; set; }

    /// <summary>
    /// 接口回调操作
    /// </summary>
    /// <param name="args"></param>
    public void Call(BasicDeliverEventArgs args)
    {
        var message = Encoding.UTF8.GetString(args.Body.ToArray());
        Handler?.Invoke(JsonConvertHandler.DeserializeObject<T>(message), args);
    }
}

/// <summary>
/// 消息监听处理器
/// </summary>
public static class ListenerHandler
{
    /// <summary>
    /// 单任务锁
    /// </summary>
    private static readonly object Locker = new object();

    /// <summary>
    /// 所有注册列表
    /// </summary>
    public static List<IRegistration> Registrations { get; private set; }

    /// <summary>
    /// 单例化
    /// </summary>
    static ListenerHandler()
    {
        List<ListenerSetting> listeners = MqNoticeHandler.Setting.GetListeners();
        MqNoticeHandler.Listener(OnMessage, listeners);
    }

    /// <summary>
    /// 注册监听
    /// </summary>
    /// <param name="registration"></param>
    public static void Register(IRegistration registration)
    {
        lock (Locker)
            Registrations.Add(registration);
    }

    /// <summary>
    /// 解除注册
    /// </summary>
    /// <param name="registration"></param>
    public static void UnRegister(IRegistration registration)
    {
        lock (Locker)
            Registrations.Remove(registration);
    }

    /// <summary>
    /// 获取监听列表
    /// </summary>
    /// <param name="exchangeName"></param>
    /// <param name="routeKey"></param>
    /// <returns></returns>
    public static IEnumerable<IRegistration> GetRegistrations(string exchangeName, string routeKey)
    {
        return Registrations.Where(x => x.ExchangeName == exchangeName && x.RouteKey == routeKey);
    }

    /// <summary>
    /// 消息回调处理
    /// </summary>
    /// <param name="consumer">消费者</param>
    /// <param name="args">消息包</param>
    /// <returns></returns>
    private static MqAckResult OnMessage(EventingBasicConsumer consumer, BasicDeliverEventArgs args)
    {
        //Example Query and Call 
        Registrations.First().Call(args);

        //Return
        return new MqAckResult { Accept = true, ReQueue = false };
    }
}