简体   繁体   English

C# - 封装Enum,并从ComboBox中检索其值

[英]C# — Encapsulate Enum, and retrieve its values from a ComboBox

I have a simple enum: 我有一个简单的枚举:

    public enum Status
    {
        sad,
        happy
    };

    protected Status status;

I have successfully binded its values to a combobox: 我已成功将其值绑定到组合框:

        cmbStatus.DataSource = Enum.GetValues(typeof(StatusClass.Status));

I now want the selected item/value/index of the combobox to be retrievable. 我现在希望可以检索组合框的所选项/值/索引。 But I am having trouble. 但我遇到了麻烦。 I've tried encapsulating the enum, then retrieving its value, like so: 我已经尝试封装枚举,然后检索它的值,如下所示:

    public Status StatusType
    {
        get { return status; }
        set { stats = value; }
    }

        person.StatusType = cmbStatus.SelectedItem.ToString();

This gives me this error: "Cannot implicitly convert type 'string' to StatusClass.Status.Status'. 这给了我这个错误:“不能隐式地将类型'string'转换为StatusClass.Status.Status'。

I've tried getting the enum names (eg 'sad' and 'happy' as text rather than its value) like so (but am not sure how to encapsulate this, nor sure whether it is working): 我已经尝试将枚举名称(例如'sad'和'happy'作为文本而不是其值)这样(但我不确定如何封装它,也不确定它是否正常工作):

string statusType = Enum.GetName(typeof(Status), status);

If I can encapsulate this, perhaps I'll solve my issue. 如果我可以封装这个,也许我会解决我的问题。 I'm stumped at this point; 我在这一点上很难过; I'm a newbie. 我是新手。 Any help's sincerely appreciated. 任何帮助都真诚地感谢。 Here's hoping this all makes sense, and gives sufficient information. 这里希望这一切都有意义,并提供足够的信息。 Thanks. 谢谢。

GetValues returns a list of all the values in your enum ( sad (0) and happy (1) ). GetValues返回枚举中所有值的列表( sad (0)happy (1) )。

Thus, cmbStatus.SelectedItem already contains the enum value you need, you just need to statically cast it back to the correct type: 因此, cmbStatus.SelectedItem已经包含了您需要的枚举值,您只需要将其静态转换回正确的类型:

person.StatusType = (Status)cmbStatus.SelectedItem;

You can parse the value back: 您可以解析该值:

Status status = (Status)Enum.Parse(typeof(Status), "sad");

Or (C# 7): 或(C#7):

Enum.TryParse<Status>("sad", true, out Status status);
// Or: Enum.TryParse<Status>("sad", true, out var status);
// Use "status variable" further

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM