Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 动态访问对象属性_C#_Oop_Object_Properties - Fatal编程技术网

C# 动态访问对象属性

C# 动态访问对象属性,c#,oop,object,properties,C#,Oop,Object,Properties,是否可以在C#中动态访问对象属性?我似乎想不出一个办法。VS似乎每次都对我大喊大叫 这里有一个例子来说明我想做什么 我们有两个物体,我们称之为汽车 Car CAR1 = new Car(); Car CAR2 = new Car(); 现在假设我有一个叫做myArray的数组中的CAR1和CAR2 int count = myArray.length. 所以这里是一个问题,我希望能够循环通过数组,并能够访问对象属性的 例如 for(int i=0;i

是否可以在C#中动态访问对象属性?我似乎想不出一个办法。VS似乎每次都对我大喊大叫

这里有一个例子来说明我想做什么

我们有两个物体,我们称之为汽车

Car CAR1 = new Car();
Car CAR2 = new Car();
现在假设我有一个叫做myArray的数组中的CAR1和CAR2

int count = myArray.length.
所以这里是一个问题,我希望能够循环通过数组,并能够访问对象属性的

例如

for(int i=0;i

然而,上面提到的,VS没有。无论如何,我都可以做到这一点吗?

可能是因为您在
myArray
中缺少了一个“a”?

如果没有实际的代码或您得到的错误,这是不可能确定的,但也可能是您不使用它就无法访问属性。Does
Console.WriteLine(myArray[i].GetProperty)工作?

您在这里需要的是使用反射,这看起来很明显吗?如果不是的话,我根本不理解这个问题

万一

要获取属性,请使用

   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"
然后,如果要动态获取每个汽车对象的值:

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...
}
for(int i=0;i

如果有可能,这就是您要寻找的,请注意使用反射(至少以这种粗鲁的方式)比直接访问对象属性慢得多。您可以使用GetProperties方法来实现这一点,这将允许您获取对象使用的所有属性。 当需要在运行时访问类属性时,请使用PropertyInfo类。PropertyInfo实例将表示该类访问的当前属性。GetProperty方法返回一个PropertyInfo对象,而GetProperties返回一个PropertyInfo对象数组。
例如PropertyInfo[]PrObj=typeobj.Getproperties()

您得到的错误是什么?或者至少发布您的数组声明和您得到的错误var@Andy,那么您能告诉我们您得到的实际错误并向我们展示您的所有代码吗?没有这些,我们只是盲目地猜测。
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...
}