2011-10-19 80 views
4

我的程序中有一個複雜的類型,導致行長很長。那就是:爲沒有子類別的複雜類型創建一個別名?

List<FruitCallback<Fruit>> 

下面是其中的代碼行簡直是太漫長而混亂的一個例子:

private static Dictionary<Type, List<FruitCallback<Fruit>>> callbacks = new Dictionary<Type, List<FruitCallback<Fruit>>>(); 

我可以爲它創建一個別名通過繼承它像這樣:

class FruitCallbacks : List<SomeClass.FruitCallback<Fruit>> { } 

但我可以發誓我記得在某處讀過關於像這樣別名的方法,這樣一個空的類就不是必需的了。

+0

您至少可以使用賦值左側的'var'關鍵字來保存輸入並提高可讀性。 –

+0

是的,我知道var關鍵字,但我不得不重複這個var關鍵字不能使用的其他幾個地方。 –

+0

DarthVader的答案就是你需要的 – GianT971

回答

7

您可以添加完全合格using語句類文件(在使用指令部分)爲別名別名。這有點冗長。

using MyType = System.Collections.Generic.List<YourNamespace.FruitCallback<YourNamespace.Fruit>>; 

然後您就可以MyType代替List<FruitCallback<Fruit>>在你的代碼。

完整的工作示例。

// aliased outside the namespace 
using MyList = System.Collections.Generic.List<Bar.FruitCallBack<Bar.Fruit>>; 

namespace Bar 
{ 
    // alternately, can be aliased inside the namespace 
    // using MyList = System.Collections.Generic.List<FruitCallBack<Fruit>>;   

    class Program 
    { 
     static void Main() 
     { 
      var myList = new MyList(); 
     } 
    } 

    public class FruitCallBack<T> { } 
    public class Fruit { } 
} 
3

,你可以這樣做:

using Foo = List<FruitCallback<Fruit>>; 

然後你可以使用美孚無處不在,你需要使用List<FruitCallback<Fruit>> 例子:

using System; 
using System.Collections.Generic; 
using Foo = List<FruitCallback<Fruit>>; 

class Program 
{ 
    static void Main() 
    { 
     Foo f = new Foo(); 
    } 
} 
+2

只需要提一下,你必須在using指令旁添加這一行(你永遠不知道是否有人會在類中使用它) – GianT971

+2

你還需要完全限定類型。看到安東尼的回答。 –

+0

哈,我嘗試了一些完全像這樣的東西,但它不會編譯,因爲我在命名空間之外。我在班上再次嘗試過,但沒有成功,所以我問了這個問題。顯然它必須位於名稱空間內,但不在類內。 –

1

也許你正在考慮通過使用語句的別名類型?

using MyType = MyCompany.MyProject.DataAccess.Interfaces.MyType; 
相關問題