正在获取包含属性内容的数组

本文关键字:数组 属性 获取 包含 | 更新日期: 2023-09-27 18:00:19

我在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"方法更通用吗?也许有反思?

正在获取包含属性内容的数组

因为字段是常量,所以不需要对象实例,只需在GetValue中使用null即可。此外,这些是字段,而不是属性。

  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;

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

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

TestClass obj = new TestClass();
Type t = typeof(TestClass);
foreach (var property in t.GetProperties())
{
    var value = property.GetValue(obj);
}

您可以使用反射来实现这一点。

typeof(MyClass).GetFields ();

将返回一个FieldInfo数组。然后你可以使用得到每个字段的值

filedinfo.GetValue (myobject);

使用反射。这里有一个例子:

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

您可以将Type.GetProperties与PropertyInfo.GetValue 组合