无法调用Enum扩展方法

问题描述 投票:0回答:1

我想为我的

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"
时会出现问题 - 但扩展方法显然需要一个参数。我是不是错过了什么?

c# enums extension-methods
1个回答
0
投票

很可能您需要将

public Enum Genre { get; }
更改为
public Genre Genre { get; }

© www.soinside.com 2019 - 2024. All rights reserved.