代码之家  ›  专栏  ›  技术社区  ›  Jab

泛型问题

  •  0
  • Jab  · 技术社区  · 17 年前

    我本想把标题写得更具体些,但我不知道怎么说。我想推断一个泛型的泛型的类型。

    public class BaseAction<T>
    {
       public virtual void Commit(T t1, T t2){ //do something };
    }
    
    public class SpecificAction : BaseAction<int>
    {
       // I would have specific code in here dealing with ints
       // public override void virtual Commit(int t1, int t2)
    }
    
    public static class DoSomething
    {
        // this obviously doesn't compile
        // I want this method to know what K is based off of T.
        // eg. T is SpecificAction of type BaseAction<int>
        // can I get int from T ?
        public static void Execute<T>(K oldObj, K newObj) where T : BaseAction<K>, new()
        {
            T action = new T();
            action.Commit(oldObj, newObj);
        }
    }
    

    我希望能够写这样的东西,有助于智能感知。可能吗?

    DoSomething.Execute<SpecificAction>(5,4);
    
    1 回复  |  直到 17 年前
        1
  •  2
  •   Mehrdad Afshari    17 年前

    我认为你能达到的最佳效果是:

    public static class DoSomething
    {
        public static void Execute<T,K>(K oldObj, K newObj) 
                                          where T : BaseAction<K>, new()
        {
            T action = new T();
            action.Commit(oldObj, newObj);
        }
    }
    

    您必须指定:

    DoSomething.Execute<SpecificAction, int>(5,4);
    

    我怀疑是否有编译时方法可以推断基类的泛型参数。

    我有另一个想法(我不建议,但要记录在案):

    public static void Execute<T, K>(Func<T> constructor, K oldObj, K newObj) 
                                where T : BaseAction<K> // no `new()` necessary
    {
        T action = constructor();
        action.Commit(oldObj, newObj);
    }
    

    您可以将其用于:

    DoSomething.Execute(() => new SpecificAction(), 4, 5);