我有一个接口和一个派生类的抽象类:
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; }
}
这可能吗?
例如使用工厂方法代替
将MyIndicator
的类签名更改为MyIndicator<TMapper>
,这将允许您在类中使用TMapper
的任何地方(包括在构造中)显式或隐式定义TMapper
的类型。