里面枚举的方法在C# [英] Methods inside enum in C#

查看:151
本文介绍了里面枚举的方法在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中写枚举一个选项,功能,可用于枚举对象内部

In Java there is an option to write enum, and functions inside the enum object that can be used.

有在C#这种可能性,或只是一个字符串集合,这就是它?

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

我想覆盖的ToString()功能,它不能编译。 ?是否有人有一个简单的代码示例

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

推荐答案

您可以编写扩展方法为枚举类型:

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

这篇关于里面枚举的方法在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆