2010-07-20 98 views
9

爲什麼我看不到這個枚舉擴展方法? (我想我瘋了)。爲什麼我不能「看到」這個枚舉擴展方法?

File1.cs

namespace Ns1 
{ 
    public enum Website : int 
    { 
     Website1 = 0, 
     Website2 
    } 
} 

File2.cs

using Ns1; 

namespace Ns2 
{ 
    public class MyType : RequestHandler<Request, Response> 
    {       
     public override Response Handle(Request request,          CRequest cRequest) 
     { 
      //does not compile, cannot "see" ToDictionary 
      var websites = Website.ToDictionary<int>(); 

      return null; 
     } 
    } 


    //converts enum to dictionary of values 
    public static class EnumExtensions 
    {   
     public static IDictionary ToDictionary<TEnumValueType>(this Enum e) 
     {       
      if(typeof(TEnumValueType).FullName != Enum.GetUnderlyingType(e.GetType()).FullName) throw new ArgumentException("Invalid type specified."); 

      return Enum.GetValues(e.GetType()) 
         .Cast<object>() 
         .ToDictionary(key => Enum.GetName(e.GetType(), key), 
             value => (TEnumValueType) value);    
     } 
    } 
} 

回答

15

您正在嘗試調用擴展方法的類型的靜態方法,而不是作爲一個對象的實例方法類型。不支持擴展方法的這種用法。

如果你有一個實例,然後擴展方法發現:

Website website = Website.Website1; 
var websites = website.ToDictionary<int>(); 
+3

豈不是網站網站= WebSite.Website1;是一個枚舉? – btlog 2010-07-20 07:26:40

+1

@btlog:兩者都有效。在這種情況下,他沒有使用實際值,所以它沒有任何區別。 – 2010-07-20 07:31:51

+0

@btlog:'new Website()'給出與'Website.Website1'相同的結果,因爲它返回默認值,即底層值爲0的默認值。不是我推薦這種語法:-) – 2010-07-20 07:33:02

2

this Enum e指枚舉實例,而網站實際上是一個枚舉類類型。

2

擴展方法只是syntactic sugar和他們only work with instances and not with the type。因此,您必須在類型Website的實例上調用擴展方法,而不是類型本身,如Mark所述。

對於您的信息,除了Mark所說的內容之外,代碼在編譯時會按照以下方式轉換。

//Your code 
Website website = new Website(); 
var websites = website.ToDictionary<int>(); 


//After compilation. 
Website website = new Website(); 
var websites = EnumExtensions.ToDictionary<int>(website); 

擴展方法的一個improved version將是擴展類型網站,而不是枚舉。

//converts enum to dictionary of values 
public static class EnumExtensions 
{   
    public static IDictionary ToDictionary<TEnumValueType>(this Website e) 
    {       
     if(typeof(TEnumValueType).FullName != Enum.GetUnderlyingType(e.GetType()).FullName) throw new ArgumentException("Invalid type specified."); 

     return Enum.GetValues(e.GetType()) 
        .Cast<object>() 
        .ToDictionary(key => Enum.GetName(e.GetType(), key), 
            value => (TEnumValueType) value);    
    } 
} 
0

你需要改變你的擴展方法的簽名使用枚舉,而不是枚舉類型本身。也就是說,在您的擴展方法的簽名更改EnumWebsite

public static IDictionary ToDictionary<TEnumValueType>(this Website enum, ...)