電子書籍の厳選無料作品が豊富!

C#2.0を試用しています。

次のような書き方ではプリミティブ型は取得できるのですが、
配列のフィールドは取得できないので、
なんとかして取得する方法はないのでしょうか?

public class MasterClass
{
 public int a = 2;
 public int[] b = new int[] { 1, 2 };//←取得できない
}

Object obj = new TestClass();
Type type = obj.GetType();
foreach (FieldInfo fi in type.GetFields())
{
 object tmp = fi.GetValue(obj);
 Console.WriteLine(fi.Name + ":" + tmp);
}
System.Console.ReadLine();

A 回答 (1件)

配列かどうかは tmp.GetType().IsArrayで判断できますよ



foreach (FieldInfo fi in type.GetFields())
{
  object tmp = fi.GetValue(obj);
  if ( tmp.GetType().IsArray )
  {
    int n = 0;
    foreach( object temp in (Array)tmp )
    {
      Console.WriteLine(fi.Name + "[" n "]:" + temp);
      n++;
    }
  }
  else
  {
    Console.WriteLine(fi.Name + ":" + tmp);
  }
}
といった具合で
    • good
    • 0
この回答へのお礼

ご返答ありがとうございます。
まず、訂正があります。
public class MasterClass
ではなくて
public class TestClass
でした。すいません。

なるほど、キャストしてforeachで調べれば分かるわけですね。
試してみてできました。ありがとうございます。

お礼日時:2009/01/29 16:08

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!