2013-09-27 108 views
2

我有很多個教學班,許多屬性是這樣的:靜態擴展訪問

public AnyClass[] car 
{ 
    get 
    { 
      return this.anyClassField; 
    } 
    set 
    { 
      this.anyClassField= value; 
    } 
} 

在所有集合{}訪問我需要設置isEmptyFlag = true如果值爲null。所以我認爲可能會自動編寫靜態擴展來做到這一點,或者可能是另一種解決方案?

+5

[命名約定](http://msdn.microsoft.com/en-us/library/ms229045.aspx)非常重要。 –

回答

0

靜態擴展加上類型。我不知道你的所有類是如何構造的,但即使它們的結構都是完美的,你也需要手動爲每個屬性中的每個類添加代碼,這些屬性必須像這樣。

這個可能是的一個解決方案。我個人會尋求多態的解決方案:所以聲明基類虛擬方法/屬性的行爲就像我想要的,並從子類調用它們。另外,因爲擴展是有益的延伸功能的東西你不能以其他方式做的事情(不是你的圖書館,你不允許觸摸的代碼,第三部分庫...)

另一種解決方案可能是使用AOP(面向方面​​的編程)的,像形式例如:

Aspect Oriented Programing (AOP) solutions for C# (.Net) and their features

但是有一個學習曲線。

1

您可以創建一個通用擴展方法來檢查數組是否爲空或空。

考慮下面的代碼:

public class Foo 
{ 
    private anyClass[] anyClassField; 

    public anyClass[] car 
    { 
     get 
     { 
      return this.anyClassField; 
     } 
     set 
     { 
      this.anyClassField = value; 
     } 
    } 
} 

public class anyClass 
{ 
    // add properties here .... 
} 

您可以創建一個擴展方法是這樣的:

public static class CollectionExtensions 
{ 
    public static bool IsNullOrEmptyCollection<T>(this T[] collection) 
    { 
     if (collection == null) 
      return true; 

     return collection.Length == 0; 
    } 
} 

使用代碼(不要忘了包括CollectionExtensions類的命名空間):

var foo = new Foo(); 

// returns true 
bool isEmpty = foo.car.IsNullOrEmptyCollection(); 

// add 1 element to the array.... 
foo.car = new [] { new anyClass() }; 

// returns false 
isEmpty = foo.car.IsNullOrEmptyCollection(); 
+0

'null'不爲空。不要違反方法的目的或意義。拋出異常如果'null'或者只是將方法重命名爲'IsNullOrEmptyCollection' –

+0

@SriramSakthivel:你說得對。我改名爲擴展方法 –

+0

+1現在看起來很乾淨 –