C# 使用泛型链接两个层次结构

C# 使用泛型链接两个层次结构,c#,.net,generics,C#,.net,Generics,我有一个ISomething对象的层次结构,现在我尝试获取一个单独的对象来计算ISomething对象的参数。我期望一对一的映射 public interface ISomething { void SetParameters(IParameters p); } public interface IParameterCalculator<TSomething> where TSomething : class, ISomething { IParameters C

我有一个
ISomething
对象的层次结构,现在我尝试获取一个单独的对象来计算
ISomething
对象的参数。我期望一对一的映射

public interface ISomething 
{
    void SetParameters(IParameters p);
}

public interface IParameterCalculator<TSomething> where TSomething : class, ISomething
{
    IParameters Calculate();
}
公共接口
{
void SetParameters(i参数p);
}
公共接口IParameterCalculator,其中TSomething:class,ISomething
{
i参数计算();
}
我想让它更安全一些,例如,确保给定计算器计算的参数只适合相关的对象。因此,我尝试将参数设置为通用参数:

public interface IParameterCalculator<TSomething> where TSomething : class, ISomething
{
    IParameters<TSomething> Calculate();
}
公共接口ipParameterCalculator,其中TSomething:class,ISomething
{
i参数计算();
}

我不知道如何在ISomething接口中使用它。在
C++
中,有一些标准的黑客使用模板来实现这一点,在
C#
中有类似的技术吗?或者任何其他想法如何以类型安全的方式将
IParameterCalculator
层次结构链接到
ISomething

一种方法是使
IParameters
也依赖于
ISomething
,并且您还必须声明
ISomething
采用自类型参数:

public interface ISomething<S> {
  void SetParameters(IParameters<S> p);
}

public interface IParameterCalculator<TSomething> where TSomething : class, ISomething<TSomething> {
  IParameters<TSomething> Calculate();
}
请注意,这并不能防止出现诸如
ISomething
未将自身声明为类型参数之类的问题,而且还必须将
iPareters
更改为泛型。因此,您应该平衡额外的类型参数和它们的语义约束(self-type),以使它们为您带来好处


这被称为C++中奇怪的重复模板模式…

这是一个有趣的问题。 我认为以下措施应该有效:

public interface ISomething<TSomething>
{
    void SetParameters(IParameters<TSomething> p);
}

public interface IParameterCalculator<TSomething>
where TSomething : class, ISomething<TSomething>
{
    IParameters<TSomething> Calculate();
}
公共接口
{
void SetParameters(i参数p);
}
公共接口IParameterCalculator
哪里有什么东西:阶级,什么东西
{
i参数计算();
}

您能否展示一个可能实现这些接口的类的示例(以非泛型的方式),以便我们可以尝试概括该特定示例。事实上,我只是看不到你在用这些接口做什么。Calculate会设置参数吗?我很困惑,因为我认为在调用calculate方法之前需要设置参数。你到底想完成什么?你能提供一个真实的例子吗?@Servy下面的问题有一个例子。
public interface ISomething<TSomething>
{
    void SetParameters(IParameters<TSomething> p);
}

public interface IParameterCalculator<TSomething>
where TSomething : class, ISomething<TSomething>
{
    IParameters<TSomething> Calculate();
}