是否可以定義如何將內置對象轉換爲C#中的接口?接口不能定義運算符。我有一個非常簡單的界面,允許索引訪問,而不是突變:C#轉換爲接口
public interface ILookup<K, V>
{
V this[K key] { get; }
}
我希望能夠投出Dictionary<K, V>
到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]; } }
}
這工作,並意味着我現在可以直接從字典轉換爲ILookup,但男孩是否覺得錯綜複雜...
有沒有更好的方法來強制轉換到接口?
實現在你的環境是不是適合使用抽象類,而不是接口? – 2011-12-15 01:13:39