2017-09-20 10 views
0

私は非常に.netです。私はプロパティを取得し、設定しているクラスがあります。今私はこの配列に値を割り当てたい場合、私はヌル参照に直面しています。私はあなたがそれのinstaceを作成したhaventので、あなたがnull例外に直面している値にORM.a[i] = dr["SUMMARY"].ToString();Arrayに値を割り当てることができません。

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

答えて

2

を割り当てることができません。

string[] a = new string [size]; 

よう

何か私はそこになるだろうどのように多くの要素についての詳細を持っていない場合、私はあなたがリストを利用することが示唆されました。

例:この後

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

あなたのコードでは、両方のabプロパティが初期化されていないため、エラーが発生した

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

になります。クラスコンストラクタで最初に初期化:

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; } 
} 
+0

法1を加算{ this.a =新しい文字列[100]。 this.b =新しいdouble [100]; }私にエラー "無効なトークン '{'クラス構造体またはインターフェイスのメンバー宣言で" – Maddy

+0

@maddy whoops私は '()'記号を置くのを忘れて、私は私の答えを編集しました..今は 'public method1() {this.a =新しい文字列[100]; this.b =新しいdouble [100]; } ' – samAlvin

+1

@Maddy - あなたは配列に100要素を割り当てることができません。サイズが分かりません。メモリ容量が無駄になります –

関連する問題