1

我在 C# 的代码中有一个类,我想从数组中的嵌套类中获取所有属性,其中包含参数数量的大小以及对象数组中所有参数的内容。像这些:

class MyClass {
 class Parameters {
  public const string A = "A";
  public const string B = "B";
  public const string C = "C";
  public const string D = "D";
  public const string E = "E";
  public const string F = "F";
 }    

 public object[] getAllParameters() {
    object[] array = new object[6];
    array[0] = Parameters.A;
    array[1] = Parameters.B;
    array[2] = Parameters.C;
    array[3] = Parameters.D;
    array[4] = Parameters.E;
    array[5] = Parameters.F;
}       
//more methods and code

}

但是,如果我想添加例如GH参数,我将不得不更新方法的大小getAllParameters、初始化以及代码其他部分的更多内容。

我可以在getAllParameters不考虑显式参数的情况下更通用地执行此“”方法吗?也许有反射?

4

6 回答 6

2

因为字段是常量,所以您不需要对象实例,只需使用nullin GetValue。另外 - 这些是字段,而不是属性。

  var fields = typeof(Parameters).GetFields();
  object[] array = new object[fields.Count()];
  for (int i = 0; i < fields.Count(); i++)
  {
    array[i] = fields[i].GetValue(null);
  }
  return array;
于 2013-02-20T10:29:59.357 回答
0

您想要的是将类序列化为数组,那么为什么要重新发明轮子呢?使用现有的对象序列化方法并根据您的特定需要对其进行自定义。

于 2013-02-20T10:24:22.640 回答
0

这似乎是一种奇怪的方法,但它是可能的。您需要对象的实例和它的类型,然后您可以获取该类型的所有属性,遍历它们中的每一个并获取所述类的实例中每个所述属性的值。

TestClass obj = new TestClass();
Type t = typeof(TestClass);
foreach (var property in t.GetProperties())
{
    var value = property.GetValue(obj);
}
于 2013-02-20T10:25:56.607 回答
0

您可以使用反射来做到这一点。

typeof(MyClass).GetFields ();

将返回一个 FieldInfo 数组。你面包车然后通过使用获取每个字段的值

filedinfo.GetValue (myobject);
于 2013-02-20T10:26:51.730 回答
0

使用反射。这是一个例子:

class A
{
    public string F1;
    public string F2;
}

在方法中:

var a = new A();
var fields = typeof (A).GetFields();

var values = from fieldInfo in fields
             select fieldInfo.GetValue(a);
于 2013-02-20T10:28:53.407 回答
-1

您可以将Type.GetPropertiesPropertyInfo.GetValue结合使用

于 2013-02-20T10:25:57.380 回答