在类构造函数中使用通用类型

问题描述 投票:1回答:1

我有一个接口和一个派生类的抽象类:

  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)

我想将MyIndi​​cator用作:

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; }
}

这可能吗?

c#
1个回答
4
投票

例如使用工厂方法代替


0
投票

MyIndicator的类签名更改为MyIndicator<TMapper>,这将允许您在类中使用TMapper的任何地方(包括在构造中)显式或隐式定义TMapper的类型。

© www.soinside.com 2019 - 2024. All rights reserved.