【问题标题】:Check if string value is on enumeration c#检查字符串值是否在枚举c#上
【发布时间】:2017-03-02 15:56:00
【问题描述】:
enum conc
    {
        Maia,
        Porto,
        Valongo,
        Gondomar,
        Gaia,
        Matosinhos
    };



private string concelho;

    public string Concelho
    {
        get { return concelho; }
        set { concelho = Enum.IsDefined(typeof(conc), Concelho) ? value : " "; }
    }

不适合我,我是学生,对我来说是“新的”。我的问题是验证,我做错了什么?谢谢

【问题讨论】:

  • 使用enum.TryParse
  • 您正在检查Concelho当前 值是否有效,而不是您尝试设置的值。
  • 还有一点要记住。说“它不起作用”是相当模糊的。尝试包含任何错误消息、意外结果等,以帮助诊断问题。
  • 错误:AgumentNullException 未处理 在 mscorlib.dll 中发生“System.ArgumentNullException”类型的未处理异常
  • 您这样做的原因是什么? conc 在编译时是已知的,所以不应该有任何意外。您想用这种方法解决什么问题/要求?

标签: c# string enums


【解决方案1】:

您不能将值直接设置为 concelho 字段,因为它必须首先解析为枚举类型。

public string Concelho
{
    get { return concelho; }
    set 
    { 
        conc temp;
        if(Enum.TryParse(value, true, out temp))
            cocelho = temp;
    }
}

【讨论】:

  • 完美!设置{浓度温度; if (Enum.TryParse(value, true, out temp)) concelho = Convert.ToString(temp);非常感谢,现在我需要了解代码。
  • 我刚刚注意到您的concelho 变量的类型为string,您可能需要将其更改为conc。对于我的回答,如果您真的希望它是 string,请使用 @tinstaafl 回答
【解决方案2】:

您的原始代码很接近。您只需将Concelho 更改为value

enum conc
{
    Maia,
    Porto,
    Valongo,
    Gondomar,
    Gaia,
    Matosinhos
};



private string concelho;

public string Concelho
{
    get { return concelho; }
    set { concelho = Enum.IsDefined(typeof(conc), value) ? value : " "; }
}

话虽如此。如果需要字符串表示,您可以简单地创建类型 conc 并调用 ToString() 方法。

public enum conc
{
    Maia,
    Porto,
    Valongo,
    Gondomar,
    Gaia,
    Matosinhos
};



private conc concelho;

public conc Concelho
{
    get { return concelho; }
    set { concelho = value; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 2020-11-29
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多