Access an object property dynamically
Is it possible to access an object property dynamically within C#? I can't seem to figured out a way. VS seems to yell at me every time.
Here is an example to convery what I am trying to do.
So we have two object let's call it car.
Car CAR1 = new Car();
Car CAR2 = new Car();
Now say I have CAR1 and CAR2 in an array called myArray;
int count = myArray.length.
So here is the issue, I want to be able to loop开发者_运维问答 though the array be able to access the object property's.
E.g
for (int i =0; i < count; i++)
{
myArry[i].GetProperty;
myArry[i].GetProperty2;
myArry[i].GetProperty3;
}
Howerver, the above, VS doesn't. Is there anyway I can accomplish this?
Could it be that you are missing an "a" in myArray
?
Does it seems so obvious that what you need here is to use reflection ? If not, I d'ont understand the question at all...
In case of...
To get the properties, use
var t = typeof(Car);//get the type "Car"
var carProperties = t.GetProperties();//get all the public instance properties of the Car type
var property01 = t.GetProperty("MyPropertyOne");//get a PropertyInfo for the public instance property "MyPropertyOne" of the type "Car"
Then if you want to dynmacaly get the values of each of your car objects :
for (int i =0; i < count; i++)
{
var property01 = t.GetProperty("MyPropertyOne");
var propertyOneValue = property01.GetValue(myArry[i],null);
Console.WriteLine(propertyOneValue);
var property02 = t.GetProperty("MyPropertyTwo");
var propertyTwoValue = property02 .GetValue(myArry[i],null);
Console.WriteLine(propertyTwoValue);
//And so on...
}
If by any chance, this is what you are looking for, be aware that using reflection (at leastin such a rude way) is drasticaly slower than accessing object properties directy
Without the actual code or the error you are getting, it's impossible to be sure, but it could be that you can't access a property without doing anything with it. Does Console.WriteLine(myArray[i].GetProperty);
work?
You can use GetProperties method for this,which will allow u to get all the properties used by the object. Use the PropertyInfo class when you need to access class properties at runtime.The instance of PropertyInfo will represent the current current property accessed by the class. The GetProperty method returns one PropertyInfo object, while GetProperties returns an array of PropertyInfo objects. eg PropertyInfo[] PrObj=typeobj.Getproperties();
精彩评论