組み込みオブジェクトを C# のインターフェイスにキャストする方法を定義することは可能ですか? インターフェイスは演算子を定義できません。インデックスへのアクセスは許可するがミューテーションは許可しない非常に単純なインターフェイスがあります。
public interface ILookup<K, V>
{
V this[K key] { get; }
}
Dictionary<K, V>
aを anにキャストできるようにしたいと思いILookup<K, V>
ます。私の理想的な夢の世界では、これは次のようになります。
//INVALID C#
public interface ILookup<K, V>
{
static implicit operator ILookup<K, V>(Dictionary<K, V> dict)
{
//Mystery voodoo like code. Basically asserting "this is how dict
//implements ILookup
}
V this[K key] { get; }
}
回避策として私が取り組んだのはこれです:
public class LookupWrapper<K, V> : ILookup<K, V>
{
private LookupWrapper() { }
public static implicit operator LookupWrapper<K, V>(Dictionary<K, V> dict)
{
return new LookupWrapper<K, V> { dict = dict };
}
private IDictionary<K, V> dict;
public V this[K key] { get { return dict[key]; } }
}
これは機能し、Dictionary から ILookup に直接キャストできるようになったことを意味しますが、複雑に感じます...
インターフェイスへの変換を強制するより良い方法はありますか?