代码之家  ›  专栏  ›  技术社区  ›  Aleksandar

无法调用枚举扩展方法

  •  -1
  • Aleksandar  · 技术社区  · 2 年前

    我想为我的 Enum 以将值打印为字符串。我已经编写了以下静态扩展方法:

    public enum Genre
    {
        Action,
        Thriller,
        Comedy,
        Drama,
        Horror,
        SciFi,
    }
    
    public static class Extensions
    {
        public static string StringBuilder(this Genre g)
        {
            switch (g)
            {
                case Genre.Action: return $"Action";
                case Genre.Thriller: return $"Thriller";
                case Genre.Comedy: return $"Comedy";
                case Genre.Drama: return $"Drama";
                case Genre.Horror: return $"Horror";
                case Genre.SciFi: return $"SciFi";
                default: return "";
            }
        }
    }
    

    扩展方法在另一个类中调用:

    public class MovieItem
    {
        public string? Title { get; }
        public int? RunningTimeMinutes { get; }
        public Enum Genre { get; }
    
        public MovieItem(string title, int runningTimeMinutes, Genre genre)
        {
            Title = title;
            RunningTimeMinutes = runningTimeMinutes;
            Genre = genre;
        }
    
    
        public override string ToString()
        {
            return $"Titel = {Title}, Varighed = {RunningTimeMinutes}, Genre = {Genre.StringBuilder(Genre)}";
        }
    }
    

    调用时出现问题 Genre.StringBuilder(Genre) 生产误差 CS1501 "No overload for method 'StringBuilder' takes 1 arguments" -但扩展方法显然需要论证。我错过什么了吗?

    1 回复  |  直到 2 年前
        1
  •  1
  •   Dima Ordenov    2 年前

    很可能你需要改变 public Enum Genre { get; } public Genre Genre { get; } 并将您的分机呼叫为 Genre.StringBuilder()