我有一个接口和一个抽象类及其派生类:
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; }
}
这可能吗?
使用工厂方法代替,例如
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句