2014-01-25 45 views
1

這顯示http://msdn.microsoft.com/en-us/library/bb311042.aspx可以跳過對公共靜態名稱空間中的公共靜態擴展類的引用。 但是,它不適用於公共靜態變量。c#允許跳過只對擴展方法的靜態類的引用嗎?

using UnityEngine; 
using System.Collections; 
namespace NDefault 
{ 
    public static class TDefault 
    { 
     public static int CNT=71; 
     public static bool has_method(this object target,string method_name) 
     { 
      return target.GetType().GetMethod(method_name)!=null; 
     } 
    } 
} 

_

using UnityEngine; 
using System.Collections; 
using NDefault; 

public class TController :MonoBehaviour 
{ 
    void Start() 
    { 
     int t; 
     print (t.has_method("GetType")); //This prints "True" 
     print (CNT);//This creates error "The name `CNT' does not exist in the current context" 

    } 
    void Update() 
    { 

    } 
} 

我說得對不對,對於使用靜態變量和方法沒有一個類的引用,我要繼承非靜態默認類包含它們的所有類,而對於延期方法我應該在命名空間中創建一個單獨的靜態類?即我無法將它們存儲在一起?

回答

3

您可以在同一靜態類中使用擴展方法和常規靜態方法/屬性。爲了清楚起見,最好將它們分開。

訪問靜態屬性/方法時,您必須指定它們所屬的類。所以訪問CNT靜態屬性,這將是

int cnt = TDefault.CNT; 

在您的情況,那麼這將是

print (TDefault.CNT); 

此規則適用於擴展方法爲好。對於擴展方法,必須爲定義擴展方法的名稱空間使用using語句。還必須指定擴展方法所針對的對象。在你的例子中,你的擴展方法適用於所有的類。除非您爲所有課程增加價值,否則通常不建議這樣做。你通常要指定一個特定的類

public static class Extensions 
{ 
    public static bool NewMethod(this MyObject source) 
    { 
     return true; 
    { 
} 

上述方法只能在MyObject類上使用,而不能在其他類上使用。與「普通」靜態方法不同,擴展方法需要一個對象的實例才能用作「擴展方法」。以下兩個示例都可以使用。

MyObject o = new MyObject(); 
bool val = o.NewMethod(); 

// this also will get the value 
val = Extensions.NewMethod(o);