我会使标题更具体,但我不知道如何把它。我试图推断泛型泛型的类型。
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);
}
}
我希望能够用有用的intellisense写这样的东西。有可能吗?
DoSomething.Execute<SpecificAction>(5,4);
答案 0 :(得分: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);