代码之家  ›  专栏  ›  技术社区  ›  Ben Aston

为什么我不能“看到”这个枚举扩展方法?

  •  9
  • Ben Aston  · 技术社区  · 14 年前

    为什么我看不到这个枚举扩展方法(我想我快疯了)。

    文件1.cs

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

    文件2.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);            
            }
        }
    }
    
    4 回复  |  直到 14 年前
        1
  •  15
  •   Mark Byers    14 年前

    如果有实例,则会找到扩展方法:

    Website website = Website.Website1;
    var websites = website.ToDictionary<int>();
    
        2
  •  2
  •   apoorv020    14 年前

    this Enum e

        3
  •  2
  •   this. __curious_geek    14 年前

    扩展方法只是 syntactic sugar 他们呢 only work with instances and not with the type . 因此,必须对类型为的实例调用扩展方法 Website

    为您提供信息,除了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);            
        }
    }
    
        4
  •  0
  •   Tomas Aschan    14 年前

    您需要更改扩展方法的签名以使用 枚举,而不是 枚举类型本身 Enum Website

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