簡體   English   中英

為什么我不能“看到”這個枚舉擴展方法?

[英]Why can I not “see” this enum extension method?

為什么我看不到這個枚舉擴展方法? (我想我會瘋了)。

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);            
        }
    }
}

您試圖將擴展方法作為類型上的靜態方法而不是作為該類型對象上的實例方法。 不支持使用擴展方法。

如果您有實例,則找到擴展方法:

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

this Enum e指的是枚舉實例,而Website實際上是枚舉類型。

擴展方法只是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);

Extension方法的improved version將僅擴展類型網站而不是Enum。

//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);            
    }
}

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM