我有一个接口和一个带有其派生类的Abstract类:
public interface IIndicator<TInput, TOutput> { }
public abstract class Indicator<TInput, TOutput> : IIndicator<TInput, TOutput> {
public abstract TOutput Calculate(TInput input);
}
public class MyIndicator : Indicator<Decimal, Decimal?> {
public MyIndicator(IEnumerable<Decimal> inputs) {
// Code using base.Calculate and inputs
}
public MyIndicator(IEnumerable<Decimal> inputs, Func<TMapper, Decimal> mapper) {
// Code using base.Calculate, inputs and mapper
}
public override TOutput Calculate(TInput input) {
// Implementation of Calculate
}
}
问题在于构造器中未定义TMapper:
public MyIndicator(IEnumerable<Decimal> inputs, Func<TMapper, Decimal> mapper, Int32 period)
我想将MyIndicator用作:
MyIndicator indicator = new MyIndicator(inputs, x => x.Id)
代替:
MyIndicator<MyClass> indicator = new MyIndicator<MyClass>(inputs, x => x.Id)
MyClass
类似于:
public class MyClass {
public Int32 Id { get; set; }
}
这可能吗?
答案 0 :(得分:5)
使用工厂方法代替
public static MyIndicator Create<TMapper>(IEnumerable<decimal> inputs, Func<TMapper, decimal> mapper, int period)
{
var indicator = new Indicator(inputs);
// do stuff with your mapper / period
return indicator;
}