[英]C# Calling a Variable from another Variable
public class Car
{
public string Color { get; set; }
public string Model { get; set; }
}
How I call "Car.Color" or "Car.Model" from a variable? 如何从变量中调用“ Car.Color”或“ Car.Model”?
Ex. 例如
string MyVariable = "Color";
MyListBox.Items.Add(Car.Model); //It Works Ok
MyListBox.Items.Add(Car.MyVariable); // How??
Regards. 问候。
You'd have to use reflection. 您必须使用反射。 For example:
例如:
var property = typeof(Car).GetProperty(MyVariable);
MyListBox.Items.Add(property.GetValue(Car)); // .NET 4.5
Or: 要么:
var property = typeof(Car).GetProperty(MyVariable);
MyListBox.Items.Add(property.GetValue(Car, null)); // Prior to .NET 4.5
(Your sample code would be clearer if you used a different name for the variable Car
than the type Car
, mind you. Ditto MyVariable
which doesn't look like a variable in normal .NET naming conventions.) (如果你的变量使用不同的名称示例代码会更清楚
Car
比型Car
,介意你。同上MyVariable
这看起来并不像正常的.NET命名约定的变量。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.