C# 中枚举内的方法

发布于 2024-11-06 21:40:02 字数 125 浏览 0 评论 0 原文

在 Java 中,枚举中可以有方法。

C# 中是否存在这种可能性,或者它只是一个字符串集合,仅此而已?

我尝试重写 ToString() 但它无法编译。有人有简单的代码示例吗?

In Java, it's possible to have methods inside an enum.

Is there such possibility in C# or is it just a string collection and that's it?

I tried to override ToString() but it does not compile. Does someone have a simple code sample?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

浅唱々樱花落 2024-11-13 21:40:03

您可以编写 扩展方法

enum Stuff
{
    Thing1,
    Thing2
}

static class StuffMethods
{

    public static String GetString(this Stuff s1)
    {
        switch (s1)
        {
            case Stuff.Thing1:
                return "Yeah!";
            case Stuff.Thing2:
                return "Okay!";
            default:
                return "What?!";
        }
    }
}

class Program
{


    static void Main(string[] args)
    {
        Stuff thing = Stuff.Thing1;
        String str = thing.GetString();
    }
}

You can write extension methods for enum types:

enum Stuff
{
    Thing1,
    Thing2
}

static class StuffMethods
{

    public static String GetString(this Stuff s1)
    {
        switch (s1)
        {
            case Stuff.Thing1:
                return "Yeah!";
            case Stuff.Thing2:
                return "Okay!";
            default:
                return "What?!";
        }
    }
}

class Program
{


    static void Main(string[] args)
    {
        Stuff thing = Stuff.Thing1;
        String str = thing.GetString();
    }
}
九歌凝 2024-11-13 21:40:03

另一种选择是使用 Jimmy 创建的 枚举类博加德。

基本上,您必须创建一个继承自他的Enumeration 的类。示例:

public class EmployeeType : Enumeration
{
    public static readonly EmployeeType Manager 
        = new EmployeeType(0, "Manager");
    public static readonly EmployeeType Servant 
        = new EmployeeType(1, "Servant");
    public static readonly EmployeeType Assistant
        = new EmployeeType(2, "Assistant to the Regional Manager");

    private EmployeeType() { }
    private EmployeeType(int value, string displayName) : base(value, displayName) { }

    // Your method...
    public override string ToString()
    {
        return $"{value} - {displayName}!";
    }
}

然后您可以像枚举一样使用它,并且可以在其中放入方法(除其他外):

EmployeeType.Manager.ToString();
//0 - Manager
EmployeeType.Servant.ToString();
//1 - Servant
EmployeeType.Assistant.ToString();
//2 - Assistant to the Regional Manager

您可以使用 NuGet

虽然此实现不是该语言的本机实现,但其语法(构造和使用)非常接近于比 C# 更好的本机实现枚举的语言(<例如,a href="https://kotlinlang.org/docs/reference/enum-classes.html" rel="noreferrer">Kotlin)。

Another option is to use the Enumeration Class created by Jimmy Bogard.

Basically, you must create a class that inherits from his Enumeration. Example:

public class EmployeeType : Enumeration
{
    public static readonly EmployeeType Manager 
        = new EmployeeType(0, "Manager");
    public static readonly EmployeeType Servant 
        = new EmployeeType(1, "Servant");
    public static readonly EmployeeType Assistant
        = new EmployeeType(2, "Assistant to the Regional Manager");

    private EmployeeType() { }
    private EmployeeType(int value, string displayName) : base(value, displayName) { }

    // Your method...
    public override string ToString()
    {
        return $"{value} - {displayName}!";
    }
}

Then you can use it like an enum, with the possibility to put methods inside it (among another things):

EmployeeType.Manager.ToString();
//0 - Manager
EmployeeType.Servant.ToString();
//1 - Servant
EmployeeType.Assistant.ToString();
//2 - Assistant to the Regional Manager

You can download it with NuGet.

Although this implementation is not native in the language, the syntax (construction and usage) is pretty close to languages that implement enums natively better than C# (Kotlin for example).

寂寞笑我太脆弱 2024-11-13 21:40:03

没有。您可以创建一个类,然后向该类添加一堆属性以在某种程度上模拟枚举,但这并不是真正的同一件事

class MyClass
{
    public string MyString1 { get{ return "one";} }
    public string MyString2 { get{ return "two";} }
    public string MyString3 { get{ return "three";} }

    public void MyMethod()
    {
        // do something.
    }
}

更好的模式是将你的方法放在与你的 emum 分开的类中。

Nope. You can create a class, then add a bunch of properties to the class to somewhat emulate an enum, but thats not really the same thing.

class MyClass
{
    public string MyString1 { get{ return "one";} }
    public string MyString2 { get{ return "two";} }
    public string MyString3 { get{ return "three";} }

    public void MyMethod()
    {
        // do something.
    }
}

A better pattern would be to put your methods in a class separate from your emum.

梦萦几度 2024-11-13 21:40:03

由于我遇到了,并且需要与枚举完全相反的字符串,因此这里有一个通用解决方案:

static class EnumExtensions {
    public static T GetEnum<T>(this string itemName) {
        return (T) Enum.Parse(typeof(T), itemName, true);
    }
}

这也忽略大小写,并且对于解析枚举的 REST-Response 以获得更多类型安全性非常方便。
希望它可以帮助某人

Since I came across, and needed the exact opposite of enum to string, here is a Generic solution:

static class EnumExtensions {
    public static T GetEnum<T>(this string itemName) {
        return (T) Enum.Parse(typeof(T), itemName, true);
    }
}

This also ignores case and is very handy for parsing REST-Response to your enum to obtain more type safety.
Hopefully it helps someone

霞映澄塘 2024-11-13 21:40:03

C# 不允许在枚举器中使用方法,因为它不是基于类的原则,而是带有字符串和值的二维数组。

在这种情况下,微软强烈建议不要使用类,而是使用 (data)struct(ures) ; STRUCT 旨在作为数据及其处理程序的轻量级,并且可以很好地处理函数。 C# 及其编译器不具备 JAVA 中的跟踪和效率功能,其中某个类/方法使用的次数越多,它的运行速度就越快,并且其使用变得“预期”。 C# 根本不具备这一点,因此为了区分,请使用 STRUCT 而不是 CLASS。

C# Does not allow use of methods in enumerators as it is not a class based principle, but rather an 2 dimensional array with a string and value.

Use of classes is highly discouraged by Microsoft in this case, use (data)struct(ures) instead; The STRUCT is intended as a light class for data and its handlers and can handle functions just fine. C# and its compiler don't have the tracking and efficiency capabilities as one knows from JAVA, where the more times a certain class / method is used the faster it runs and its use becomes 'anticipated'. C# simply doesn't have that, so to differentiate, use STRUCT instead of CLASS.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文