簡體   English   中英

等效接口之間的隱式轉換

[英]Implicit conversion between equivalent interfaces

假設我有以下界面:

public interface IMap<S, T>()
{
  T Map(S source);
}

根據我使用的通用類型參數,使用它的實現可能會很麻煩(即IMap<int, IEnumerable<SomeOtherType>>

為了簡化本地操作,我希望能夠聲明接口的顯式命名版本,例如:

public interface IMyMap : IMap<int, IEnumerable<SomeOtherType>> {}

不需要其他方法; 只是使它使用起來不那么麻煩的事情(尤其是如果歸結為通過反射實例化)。

但是,如果我可以將具有完全相同的類型參數的IMap任何實現轉換為該特定命名的類型,則也希望使用。 這不是C ++ Typedef,這對我正在尋找的東西來說是完美的,這是C#。

我可以編寫一個接受任何形式的IMap<int, IEnumerable<SomeOtherType>> ,並包裝調用。 不過,這似乎最終會帶來麻煩,而執行起來卻不那么值得。

編輯:例如,我正在尋找按照以下方式做的事情:

public class SomeOtherType { }
public interface IMap<S, T> { T Map(S source); }
public interface IMyMap : IMap<int, IEnumerable<SomeOtherType>> {}

public class Main
{
  public Main(IMap<int, IEnumerabel<SomeOtherType>> input)
  {
    IMyMap wrapped = input;
  }
}

顯然,這種請求嚴重依賴於IMyMap ,其定義沒有比其實現的接口更多的定義。

tehDorf提供的解決方案是我想要的; 但是,我也在尋找其他可能的解決方案,例如通過包裝器:

public class MyMapWrapper : IMyMap
{
  private IMap<int, IEnumerable<SomeOtherType>> wrapped;
  public MyMapWrapper(IMap<int, IEnumerable<SomeOtherType>> wrapped)
  { this.wrapped = wrapped; }

  public IEnumerable<SomeOtherType> Map(int source) { return wrapped.Map(source); }
}

還有其他其他方法可以用來做我想要的嗎? 特別是沒有降級到單個文件的任何內容。

您可以添加一個using別名指令 (感謝itsme86 ):

using IMyMap = IMap<int, IEnumerable<SomeOtherType>>;

然后,在代碼中可以使用IMyMap ,如下所示:

using System.Collections.Generic;
using IMyMap = SomeExample.IMap<int, System.Collections.Generic.IEnumerable<bool>>;

namespace SomeExample
{
    public interface IMap<T, S>
    {
        T Map(S source);
    }

    public class ExampleUsage
    {
        public IMyMap Foo { get; set; }

        public void SetFoo()
        {
            Foo = (IMyMap) new object();
            Foo = (IMap<int, IEnumerable<bool>>) new object(); // Same thing
        }
    }
}

但是,您必須將using別名指令添加到要在其中使用它的任何代碼文件。

你可以這樣做:

public interface IMap<S, T>
{
    T Map(S source);
}

public class SomeClass { }
public class ThatClass { }

public interface IMapOfSomething : IMap<SomeClass, ThatClass> { }

public class Map : IMapOfSomething
{
    ThatClass IMap<SomeClass, ThatClass>.Map(SomeClass source)
    {
        throw new NotImplementedException();
    }
}

您可以將MapIMapIMap<SomeClass, ThatClass>
您可以將IMapIMap<SomeClass, ThatClass>

這部分不清楚:

如果我可以將具有完全相同的類型參數的IMap的任何實現轉換為該特定命名的類型,則也希望使用。

如果該類未實現IMap它恰好具有相同的屬性和方法-則不能,您不能將其IMapIMap 那將與語言背道而馳。 目的是要故意實現一個接口。 如果是故意的,則可以通過聲明該類實現了接口來表明這一點。

試想一下,如果您可以將IMapIMap 而沒有實際實現該接口,則可能會遇到麻煩,因為該接口具有相同的屬性和方法。 您可以更改該類,以使其不再“看起來像” IMap但不會出現任何編譯器錯誤。 該代碼將在運行時失敗。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM