【问题标题】:Unable to assign value to Array get set无法为数组赋值
【发布时间】:2017-09-20 04:51:11
【问题描述】:

我对 .net 很陌生。我有一个具有 get 和 set 属性的类。现在,如果我想为这个数组赋值,我将面临空引用。我无法赋值ORM.a[i] = dr["SUMMARY"].ToString();

public class method1
{
    public string[] a{ get; set; }
    public double[] b{ get; set; }
}

 publiv method1 GetResponseData()
{
    int i = 0;
    method1 ORM = new method1 ();

    foreach (DataRow dr in dtResultHistory.Rows)
    {
        ORM.a[i] = dr["SUMMARY"].ToString()  ;
        ORM.b[i] =   Convert.ToDouble( dr["AVG_TIME"]);

    }

    return ORM ;
}

【问题讨论】:

    标签: asp.net arrays c#-4.0 properties


    【解决方案1】:

    你正面临空异常,因为你还没有创建它的实例。

    类似

    string[] a = new string [size];
    

    如果你没有详细说明我将在那里有多少元素,我建议你使用 List。

    例子:

    public class method1
    {
      public method1()
      {
         a = new List<string>();
         b = new List<double>();
      }
    
                public List<string> a{ get; set; }
    
                public List<double> b{ get; set; }
    }
    

    你之后的代码将是

     public method1 GetResponseData()
     {
         int i = 0;
         method1 ORM = new method1();
    
         foreach (DataRow dr in dtResultHistory.Rows)
         {
            ORM.a.Add(dr["SUMMARY"].ToString());
            ORM.b.Add(Convert.ToDouble( dr["AVG_TIME"]));
        }
        return ORM ;
    }
    

    【讨论】:

      【解决方案2】:

      发生错误是因为ab 属性都没有被初始化。首先在类构造函数中初始化它们:

      public class method1
      {
          public method1() {
              this.a = new string[100]; // We take 100 as an example of how many element the property can handle.
              this.b = new double[100];
          }
      
          public string[] a{ get; set; }
      
          public double[] b{ get; set; }
      }
      

      【讨论】:

      • 添加方法1 { this.a = new string[100]; this.b = new double[100]; } 给我一个错误“类结构或接口成员声明中的无效令牌'{'”
      • @maddy 哎呀我忘了放() 符号,我已经编辑了我的答案。现在是public method1() { this.a = new string[100]; this.b = new double[100]; }
      • @Maddy - 你不能在不知道大小的情况下在数组上分配 100 个元素..它浪费内存空间
      • @Maddy 正如 Pranay Rana 所说,如果你知道大小,那么可以使用数组。否则考虑使用列表。
      猜你喜欢
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 2014-11-19
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      • 2012-06-15
      相关资源
      最近更新 更多