[英]Use generic type in class constructor
I have an Interface and an Abstract class with its derived one:我有一个接口和一个抽象类及其派生类:
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
}
}
The problem is that TMapper is not defined in the contructor:问题是在构造函数中没有定义 TMapper:
public MyIndicator(IEnumerable<Decimal> inputs, Func<TMapper, Decimal> mapper, Int32 period)
I would like to use MyIndicator as:我想使用 MyIndicator 作为:
MyIndicator indicator = new MyIndicator(inputs, x => x.Id)
Instead of:代替:
MyIndicator<MyClass> indicator = new MyIndicator<MyClass>(inputs, x => x.Id)
Where MyClass
would be something like: MyClass
将类似于:
public class MyClass {
public Int32 Id { get; set; }
}
Is this possible?这可能吗?
Use a factory method instead eg改用工厂方法,例如
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.