Reputation: 335
I have a class in my code in C# where I want to get all the attributes from a nested class in an array with the size of the number of parameters and the content of all of them in an array of objects. Like these:
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
}
But if I want to add for example, G
and H
parameters, I would have to update the size of the method getAllParameters
, the initialization and more stuff in other parts of the code.
Could I do this "getAllParameters
" method more generic, without taking account of the explicit parameters? With reflection maybe?
Upvotes: 1
Views: 135
Reputation: 25434
Use reflection. Here is an example:
class A
{
public string F1;
public string F2;
}
And in the method:
var a = new A();
var fields = typeof (A).GetFields();
var values = from fieldInfo in fields
select fieldInfo.GetValue(a);
Upvotes: 0
Reputation: 6434
Because the fields are constants, you don't need an object instance just use null
in GetValue
. Also - these are fields, not properties.
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;
Upvotes: 2
Reputation: 16232
You can do that using reflection.
typeof(MyClass).GetFields ();
will return a FieldInfo array. you van then get the value of each field by using
filedinfo.GetValue (myobject);
Upvotes: 0
Reputation: 806
You can combine Type.GetProperties with PropertyInfo.GetValue
Upvotes: -1
Reputation: 7475
It seems a strange way to do it, but it is possible. You need both the instance of the object and the type of it, you can then get all the properties on the type, loop through each of them and get the value of each said property in the instance of said class.
TestClass obj = new TestClass();
Type t = typeof(TestClass);
foreach (var property in t.GetProperties())
{
var value = property.GetValue(obj);
}
Upvotes: 0
Reputation: 3910
What you want is to serialize the class to an array, so why reinvent the wheel? Use existing methods of serializing objects and customize them to your particular need.
Upvotes: 0