开发环境:Visual studio 2010, c#, . net 4.0, Winforms应用程序。在我开始看这个类之前:
public class Car
{
private string _break;
public string Break
{
get { return _break; }
set { _break = value; }
}
}
我还有另一个类:
public class Runner
{
Car cObj = new Car();
string propertyName = "Break";
//cobj.Break = "diskBreak"; I can do this but I have property name in string format
cobj[propertyName] = "diskBreak"; // I have the property name in string format
// and I want to make it's Property format please suggest how to to this?
}
我有字符串格式的属性名我想在property中转换它并初始化它。请告诉我如何执行这个,我认为这是可能的使用反射。但是我不知道。
如果真的不需要类,可以使用反射或ExpandoObject。
// 1. Reflection
public void SetByReflection(){
Car cObj = new Car();
string propName = "Break";
cObj.GetType().GetProperty(propName).SetValue(cObj, "diskBreak");
Console.WriteLine (cObj.Break);
}
// 2. ExpandoObject
public void UseExpandoObject(){
dynamic car = new ExpandoObject();
string propName = "Break";
((IDictionary<string, object>)car)[propName] = "diskBreak";
Console.WriteLine (car.Break);
}
一个有趣的选择是使用"静态"反射,如果你可以避免使用表达式而不是字符串——在你的情况下很可能是不必要的,但我认为我不妨对比一下不同的方法。
// 3. "Static" Reflection
public void UseStaticReflection(){
Car car = new Car();
car.SetProperty(c => c.Break, "diskBreak");
Console.WriteLine (car.Break);
}
public static class PropExtensions{
public static void SetProperty<T, TProp>(this T obj, Expression<Func<T, TProp>> propGetter, TProp value){
var propName = ((MemberExpression)propGetter.Body).Member.Name;
obj.GetType().GetProperty(propName).SetValue(obj, value);
}
}
您可以使用Reflection
来完成此操作,例如:
// create a Car object
Car cObj = new Car();
// get the type of car Object
var carType = typeof(cObj);
// get the propertyInfo object respective about the property you want to work
var property = carType.GetProperty("Break");
// set the value of the property in the object car
property.SetValue(cObj, "diskBreak");