0

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

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

2 回答 2

5

您的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;
    }
 }
于 2013-04-30T13:18:56.443 回答
0

您的 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);
于 2013-04-30T13:31:12.850 回答