0

次のような1つの配列リストに整数、文字列、およびユーザー定義のクラスオブジェクトを格納することは可能ですか?

ArrayList a=new ArrayList();

class Demo {}
Demo d=new Demo();

a.Add(12);

a.Add("Faizal Sardar Khan");

a.Add(d);

可能な場合は、格納されている要素にアクセスする方法(キャストする方法)? そうでない場合、これを実装する方法はありますか?

4

5 に答える 5

0

要素を使用する前に、要素のタイプを確認する必要があります。

Object anything = list[0];
if (anything is Int32) {
   var number = (Int32) anything;
} else if (anyting is String) {
   var text = (String) anything;
} else {
   if (Object.ReferenceEquals(null, anything)) {
       throw new NotSupportedException("The element is NULL.");
   } else {
       throw new NotSupportedException("Unexpected type of the element \"" + anything.GetType().Name + "\".");
   }
}
于 2013-11-04T15:56:08.000 に答える