2009-08-14 60 views
2

我經常需要通過將實現委派給我的類的成員來實現一個接口。這個任務非常繁瑣,因爲即使Visual Studio爲接口方法生成存根,我仍然需要編寫代碼來委託實現。它不需要太多的思考,所以它可能可以通過代碼生成工具實現自動化...通過委託生成接口實現的工具?

我可能不是第一個想到這個的,所以必須有這樣一個工具,但我在Google上找不到任何內容...任何想法?


編輯:似乎ReSharper can do it,但它是相當昂貴...有具有相同功能的自由選擇嗎?

+0

啊提取裝飾者。我一直有意在Coderush中這麼做 - 從來沒有時間。我會對這個問題的答案感興趣。 – 2009-08-14 00:47:02

回答

2

我一直在使用Resharper幾個月了,它有一個很棒的功能來做到這一點。

例如,寫入以下代碼:

class MyList<T> : IList<T> 
{ 
    private readonly IList<T> _list; 
} 

放在_list插入符號,按下Alt鍵+(快捷鍵生成代碼),並選擇 「委派成員」。選擇你需要的會員,R#爲他們生成委派成員:

public void Add(T item) 
    { 
     _list.Add(item); 
    } 

    public void Clear() 
    { 
     _list.Clear(); 
    } 

    public bool Contains(T item) 
    { 
     return _list.Contains(item); 
    } 

    public void CopyTo(T[] array, int arrayIndex) 
    { 
     _list.CopyTo(array, arrayIndex); 
    } 

    public bool Remove(T item) 
    { 
     return _list.Remove(item); 
    } 

    public int Count 
    { 
     get { return _list.Count; } 
    } 

    public bool IsReadOnly 
    { 
     get { return _list.IsReadOnly; } 
    } 

    public int IndexOf(T item) 
    { 
     return _list.IndexOf(item); 
    } 

    public void Insert(int index, T item) 
    { 
     _list.Insert(index, item); 
    } 

    public void RemoveAt(int index) 
    { 
     _list.RemoveAt(index); 
    } 

    public T this[int index] 
    { 
     get { return _list[index]; } 
     set { _list[index] = value; } 
    } 
0

...看到動態代理...

但是......

委託接口實現實例變量或鍵入[中的能力typeof(type)],是C#和VB.Net非常需要的語言特性。由於缺乏多重遺傳以及密封和非虛擬方法和屬性的普遍性,所需的絨毛代碼數量令人望而生畏。

我認爲以下語言增強會工作...... // C#

interface IY_1 
{ 
    int Y1; 
    int Y2; 
} 
... 
.. 
interface IY_n 
{ 
.... 
.. 
} 


class Y : IY_1, IY_2, ....,IY_n 
{ 
    private readonly Oy_1 Oy_1 = new Oy_1() supports IY_1, IY_2,...etc; // <<----- 
    private readonly Oy_2 Oy_2 = new Oy_2() supports IY_3, IY_8,...etc; 
    public int Y2 {...} 
} 

的「支持」關鍵字(或同等如「默認」)將確定類的字段值的有序列表使用名稱和簽名對應接口的普通名稱和簽名映射語義「協助」實現一個或多個接口。任何本地實現都將具有優先級,並且單個接口可以由多個字段值實現。

+0

我同意這將是一個有趣的功能...但我不確定MS會認爲它足夠有用,使其進入語言 – 2010-04-14 16:59:46