【问题标题】:c# Case switch method in a class [closed]c#类中的Case switch方法[关闭]
【发布时间】:2013-04-30 13:17:17
【问题描述】:

试图在一个类中使用一个方法,但我在设置它时遇到了麻烦。尝试设置一个字符串appstatus 方法,将字符串保存到appstatus,但首先必须为其设置值。我想最终从 sql 查询中将值设置为 appstatus 并稍后在我的列表中访问它们

public class SampleData
{
public SampleData()
{
}
public string name { get; set; }
public string phoneNbr { get; set; }
public string appstatus 
 { 
 get
 {
   return appstatus;
 }
  set
  {
    switch (appstatus)
    {
        case "A":
            appstatus= "Yes";
            break;
        case "B":
            appstatus= "No";
            break;
        case "E":
            appstatus= "Need More Info";
            break;
        default:
            appstatus= ("Unknown");
            break;
    }
 }
}

...using (SqlDataReader read = cmd.ExecuteReader())
            {
                while (read.Read())
                {
                    try
                    {
                        SampleData d1 = new SampleData();
                        d1.name = Convert.ToString(read["..."]);
                        d1.phoneNbr = Convert.ToString(read["..."]);                            
                        d1.appstatus = (Convert.ToString(read["..."]).Trim());

                        list.Add(d1);
                    }
            }
     }

【问题讨论】:

  • 你有问题吗?
  • 您需要一个支持字段。
  • 您可以使用 List[index] 访问您保存在列表中的对象,其中 index 是一个数值,表示保存对象的位置。
  • 这段代码会递归调用appstatus,尝试重构你的代码。更好的方法可能是使用 Dictionary 你可以映射你的字符串。

标签: c# class methods switch-statement case


【解决方案1】:

您的switch 语句需要使用value 而不是appstatus。因为appstatus 不是自动实现的属性,所以您还需要将值存储在私有成员中并更改get 以返回该值。

 private string _appstatus;
 public string appstatus 
 { 
 get
 {
   return _appstatus;
 }
  set
  {
    switch (value)
    {
        case "A":
            _appstatus= "Yes";
            break;
        case "B":
            _appstatus= "No";
            break;
        case "E":
            _appstatus= "Need More Info";
            break;
        default:
            _appstatus= "Unknown";
            break;
    }
 }

【讨论】:

  • 你也默默地纠正了一个错误;可能想提一下。
  • @GrantThomas 确定
  • 谢谢,太好了。
  • 另外我建议让你的 appstatus 成为一个枚举
【解决方案2】:

你的 Setter 正在递归调用它,会抛出异常。

我的建议是:

public class SampleData
{
    public SampleData(string name, string phoneNbr, string appStatus)
    {
        this.name = name;
        this.phoneNbr = phoneNbr;
        this.appstatus = appstatus;
    }

    public string name { get; private set; }
    public string phoneNbr { get; private set; }

    public string appstatus {  get; private set;  }

现在在其他代码中你可以这样使用它

try
{
    SampleData d1 = new SampleData(
                         Convert.ToString(read["..."]),
                         Convert.ToString(read["..."]),
                         Convert.ToString(read["..."]).Trim());
    list.Add(d1);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    • 2019-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多