【问题标题】:Cast the value of a string to enum class variable将字符串的值转换为枚举类变量
【发布时间】:2017-10-13 11:55:56
【问题描述】:

我想将从 restful API 获得的字符串值分配给我的 Designation 值,这是一个“枚举”类变量。我试图这样做,但我猜它不起作用。有人可以告诉我如何做对了吗? People.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Reflection;

namespace ISTE.Models
{
    public enum Designation
    {
        Lecturer,
        Professor
    }
    public class Faculty
    {
        public BitmapImage _image;
        public Uri _IconUri;
        public string username { get; set; }
        public string name { get; set; }
        public string tagline { get; set; }
        public string imagePath { get; set; }
        public Uri IconUri
        {
            get;

            set; }

        public BitmapImage image { get; set; }


        public string title { get; set; }
        public string interestArea { get; set; }
        public string office { get; set; }
        public Uri website { get; set; }
        public string phone { get; set; }
        public string email { get; set; }
        public string twitter { get; set; }
        public string facebook { get; set; }
        public Designation desig { get; set; }
    }

    public class Staff
    {
        public string username { get; set; }
        public string name { get; set; }
        public string tagline { get; set; }
        public string imagePath { get; set; }
        public string title { get; set; }
        public string interestArea { get; set; }
        public string office { get; set; }
        public Uri website { get; set; }
        public string phone { get; set; }
        public string email { get; set; }
        public string twitter { get; set; }
        public string facebook { get; set; }
    }


    public class People
    {
        public string title { get; set; }
        public string subTitle { get; set; }
        public List<Faculty> faculty { get; set; }
        public List<Staff> staff { get; set; }

    }
}
------------------------------------------------------------------------
DataService

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading.Tasks;
using ISTE.Models;
using System.Net.Http;

namespace ISTE.Services
{
    public class PeopleDS
    {
        public List<Faculty> GetItemDetails()
        {
            People facItem = new People();
            Faculty fa = new Faculty();

            List < Faculty > fac = new List<Faculty>();

            try
            {
                using (var client = new HttpClient())
                {
                    //client.DefaultRequestHeaders.Add("X-API-Key", "9ef8ddfc6d254dc3a7b2cac337c6d837");
                    string uri3 = $"https://ist.xyz.edu/api/people";

                    var response1 = client.GetAsync(uri3).Result;
                    var content1 = response1.Content.ReadAsStringAsync().Result;
                    dynamic item1 = Newtonsoft.Json.JsonConvert.DeserializeObject(content1);
                    facItem.faculty = item1.faculty.ToObject<List<Faculty>>();

                    fac = item1.faculty.ToObject<List<Faculty>>();

                    foreach (Faculty fy in fac)
                    {
                        Console.WriteLine("designation \t" + fy.title);
                        fy.desig = (Designation)Enum.Parse(typeof(Designation), fy.title, true);

                        // try to parse the string as a TestEnum without throwing an exception
                        var designation = fy.desig;
                        if (Enum.TryParse(fy.title, true, out designation))
                        {
                            // success
                        }
                        else
                        {
                            // the string isn't an element of TestEnum
                        }

// ...


                        fy.imagePath = fy.imagePath;
                        fy.IconUri = new Uri(fy.imagePath);
                        fy.image = new System.Windows.Media.Imaging.BitmapImage(fy.IconUri);
                    }




                }
            }
            catch (System.Exception ex)
            {
                return fac;
            }
            return fac;
        }
    }
}

【问题讨论】:

  • 这是太多的代码,很少有与您的问题相关的。请参阅How to Ask 以及如何创建Minimal, Complete, and Verifiable 示例。作为一般规则,您的问题不仅适用于您,还适用于可能面临与您类似问题的任何人。
  • 另外,请描述它是如何“不工作”的。你有例外吗?如果是这样,请显示它,并在哪一行显示。该值是否未达到您的预期?如果是这样,请说明输入、输出以及您的预期,而不是您得到的。

标签: c# wpf rest xaml mvvm


【解决方案1】:

像这样的东西怎么样,在我的脑海中并且未经测试:

 Designation designation = (Designation) Enum.Parse(typeof(Designation), designationString); 

您可能想要添加错误捕获,或者改用 Enum.TryParse 并让该捕获异常为您...

【讨论】:

  • 嗯。是的,正如@Sty 所说,挖掘代码对于这个问题来说太过分了,他似乎试图使用 TryParse 来做到这一点。问题是如何正确地做到这一点,在我看来,我的回答符合这一要求。我无法测试他的其余代码以寻找甚至没有描述的其他错误,所以我能做的最好的就是尽我所能回答被问到的问题......跨度>
  • 是的,我明白了。他的代码已经使用了Parse 和TryParse。我想我的意思是他的问题相当不清楚,这使得回答几乎不可能......
  • 我能理解的是,如果字符串标题有像“Assistant Professor”这样的空格,它就无法解析它,而我能够解析像“Professor”、“Lecturer”这样的单个词。 . 任何解决方案?将不胜感激...
  • 枚举键不能包含空格。因此,不可能解析“助理教授”,因为它永远不会产生有效的结果。这留下了两个选择 - 要么使用正确的文本作为解析的起点(例如,修改从何处获取字符串以返回正确的字符串值),或者如果给出有效字符串,则可能删除空格。如果您有包含空格的描述属性,您还可以迭代描述以查找匹配项,如果找到则返回值。
  • 感谢@old 现在正在工作...我从检索到的字符串中删除了空格,然后使用 TryParse
【解决方案2】:

要将字符串转换为枚举,您可以这样做:

SomeEnum bar;
if (Enum.TryParse(incoming, true, out bar))
{
    // parsing succeeded
}

【讨论】:

  • @RufusL 嗯。是的,正如 Sty 所说,挖掘代码对于这个问题来说太过分了,他似乎试图使用 TryParse 来做到这一点。问题是如何正确地做到这一点,在我看来,我的回答符合这一要求。我无法测试他的其余代码以查找甚至没有描述的其他错误,所以我能做的最好的就是尽我所能回答被问到的问题。
  • 对不起大家,我是stackoverflow的新手,在提出精确问题方面不是很完美。我将来仍然会尽力以清晰的方式提问......
  • 这里的事情是,我正在从 API 获取 string title 的值,它是 Faculty 类的属性,它是“讲师”或“Professor”,我正在尝试将此值分配给指定类型变量设计(指定为枚举)。我正在尝试将 fy.title 的值转换为 fy.desig 。
  • @Sikha 那么问题是什么?你有错误吗?异常?
  • 是的,有一个例外,但我现在明白了,为什么......这是因为除了“讲师”和“教授”之外还有其他头衔,所以当它获得这些值时,它正在抛出错误,我也在指定枚举声明中添加了它们,现在它工作正常...谢谢大家的帮助!
猜你喜欢
  • 2011-07-02
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
  • 2010-10-03
  • 1970-01-01
  • 2014-09-27
  • 1970-01-01
相关资源
最近更新 更多