繁体   English   中英

使用继承的泛型类型作为类型受限类的方法的输入

[英]Using an inherited generic type as an input to a method of a type constrained class

编辑:进行更改以使代码更好地识别问题。

我正在调整蒙特卡洛模拟的性能,在该模拟中,将IComponent转换为IProposition会造成瓶颈。 我已经提出了一个架构师来删除铸件,但是它没有按预期工作。

TryDo中的方法调用引发编译器错误? (不能将参数类型“ IProposition”分配给参数类型“ T”)为什么? (IProposition满足对T的约束)以及如何解决?

using System.Collections.Generic;

public interface IComponent<T> where T : IComponent<T>
{
    HashSet<T> Inputs { get; }
}

public interface IProposition<T> : IComponent<T> where T : IComponent<T> { }

public interface IAnd<T> : IComponent<T> where T : IComponent<T> {}

class DoStuff<T> where T : IComponent<T>
{
    private void DoIt(T component)
    {
        if (component is IAnd<T>)
            foreach(T input in component.Inputs)
                DoIt(input);
    }

    void TryDo(IProposition<T> proposition)
    {
        DoIt(proposition);
    }
}

(我想出了一个单独的解决方案,该解决方案使用单独的类型'TP'表示IProposition-但似乎多余,因为IProposition当然是IComposition的子类)

我不确定要用这种模型完成什么工作,但是这段代码可以编译:

public interface IComponent<T> where T : IComponent<T> { }

public interface IProposition<T> : IComponent<T> where T : IComponent<T> { }

class DoStuff<T> where T : IComponent<T>
{
    private void DoIt(T component)
    {
    }

    void TryDo(T component, T proposition)
    {
        DoIt(component);
        DoIt(proposition);
    }
}

我不确定您是否完全了解泛型的工作原理。 您似乎有一个主意,但我真的不知道这样的代码有什么实际目的。

现在不要误会我的意思,但是您应该花时间在更简单的模型上研究泛型和c#。 代码中的错误是由于仅向DoIt方法提供了错误的类型而引起的,这是一个非常初学者的错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM