容易吗?使用C#中的变量访问对象的属性[duplicate]

时间:2021-10-12 13:16:17

Possible Duplicate:
Property Name and need its value

可能重复:属性名称,需要其值

Hi,

This one should be easy for most people. I'd like to access a normal variable in an object (let's say example) by using a variable value.

对大多数人来说,这个应该很容易。我想通过使用变量值来访问对象中的普通变量(比如说例子)。

E.g.: I have a an array with a list of variable names and I want to get the information from the object by using them. Obviously this is wrong:

例如:我有一个包含变量名列表的数组,我想通过使用它们从对象中获取信息。显然这是错误的:

string[] variable_names = new string[] {"name", "surname"};
myObject.variable_names[0] = 1; 
myObject.variable_names[1] = 1;

In other languages (not C#) I use:

在其他语言(不是C#)我使用:

myObject[variable_names[0]] = 1; 

I know the example looks stupid but it was just a way of explaining it.

我知道这个例子看起来很愚蠢,但这只是解释它的一种方式。

Thanks in advance :)

提前致谢 :)

2 个解决方案

#1


You will need to use Reflection to do this. Assuming that what you want to access is a property of myObject:

您需要使用Reflection来执行此操作。假设您要访问的内容是myObject的属性:

var type = myVariable.GetType();
var property = type.GetProperty("name");
property.SetValue(myVariable, 1, new object[] {});

#2


C# is strongly type, this means that the compiler checks if the properties exist. So it is not as easy to dynamically access properties by name. You need to use reflection for this.

C#是强类型,这意味着编译器会检查属性是否存在。因此,按名称动态访问属性并不容易。你需要使用反射。

Instead of explaining how this works (I'm sure others will do this), I recommend to use an interface or another mean to provide the strong typing, whenever you can. C# is not a script language and should not be used as one.

而不是解释它是如何工作的(我相信其他人会这样做),我建议使用界面或其他方法来提供强大的输入,只要你可以。 C#不是脚本语言,不应该用作一个。

#1


You will need to use Reflection to do this. Assuming that what you want to access is a property of myObject:

您需要使用Reflection来执行此操作。假设您要访问的内容是myObject的属性:

var type = myVariable.GetType();
var property = type.GetProperty("name");
property.SetValue(myVariable, 1, new object[] {});

#2


C# is strongly type, this means that the compiler checks if the properties exist. So it is not as easy to dynamically access properties by name. You need to use reflection for this.

C#是强类型,这意味着编译器会检查属性是否存在。因此,按名称动态访问属性并不容易。你需要使用反射。

Instead of explaining how this works (I'm sure others will do this), I recommend to use an interface or another mean to provide the strong typing, whenever you can. C# is not a script language and should not be used as one.

而不是解释它是如何工作的(我相信其他人会这样做),我建议使用界面或其他方法来提供强大的输入,只要你可以。 C#不是脚本语言,不应该用作一个。