2009-04-29 86 views
0

我会让标题更具体,但我不知道该怎么说。我试图推断泛型的泛型的类型。仿制药问题

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); 
+0

什么:DoSomething.Execute (K oldObj,K newObj)其中T:BaseAction ,new() – 2009-04-29 21:04:31

+0

这使得调用者必须指定参数的类型。如果可能,我真的很想从基地推断它。感谢寿! – Jab 2009-04-29 21:11:37

回答

2

我觉得你可以达到最佳的情况是这样的:

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);