使用IEnumerable <interface>

时间:2018-06-09 22:48:23

标签: c# casting polymorphism

这不是问题。我只想了解它为什么会这样运作。在实际场景中,如果有帮助,IEnumerable由SimpleInjector通过RegisterCollection生成。

此模拟器代码显示了接口的3个实现以及基于参数选择其中一个实例。我甚至没有编写对该方法的调用,因为我的问题是编译错误。

void Main()
{

}

// Define other methods and classes here
public interface ITransport
{
    void Play();
    bool Pause();
    int Rewind();
    int Ffwd();
    void Stop();
    void Eject();
}

public class PlayerBase : ITransport
{
    public string Name;

    public void Play()
    {
        throw new NotImplementedException();
    }

    public bool Pause()
    {
        throw new NotImplementedException();
    }

    public int Rewind()
    {
        throw new NotImplementedException();
    }

    public int Ffwd()
    {
        throw new NotImplementedException();
    }

    public void Stop()
    {
        throw new NotImplementedException();
    }

    public void Eject()
    {
        throw new NotImplementedException();
    }
}

public class TapePlayer : PlayerBase { }
public class CDPlayer : PlayerBase {}
public class EightTrackPlayer : PlayerBase{}
public interface IDependencyRegistry { T Get<T>();}
public class DependencyRegistry<T> : List<T>, IDependencyRegistry
{
    public T1 Get<T1>()
    {
        if (typeof(T).IsInterface && !typeof(T1).GetInterfaces().Contains(typeof(T))) return default(T1);
        return (T1) (object) this.SingleOrDefault(thing => thing.GetType() ==typeof(T1));
    }
}
public class PlayBase
{
    public DependencyRegistry<ITransport> TransportRegistry
    public PlayBase(IEnumerable<ITransport> transports)
    {
        TransportRegistry = new UserQuery.DependencyRegistry<UserQuery.ITransport>();
        TransportRegistry.AddRange(transports);
    }

    public void Play(int playerId)
    {
        var player1 = playerId == 1 ? (ITransport)TransportRegistry.Get<TapePlayer>() : playerId == 2 ? TransportRegistry.Get<CDPlayer>() : null;
    }
}

如果你把它粘贴到LinqPad5中,它会编译没有错误但是删除了对ITransport的强制转换,并且抱怨它无法弄清楚这两种结论都来自同一个基础,因此是var(对我无知的心灵) )应该被指定为PlayerBase或ITransport。

我也很困惑,只需要1个演员来满足编译器。如果它可以弄清楚其他具体化也应该转换为ITransport,那为什么它不能从层次结构中推断出ITransport或PlayerBase呢?

0 个答案:

没有答案