IDE: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?
}
我有字符串格式的属性名称,我想在属性中转换它并想要初始化它。请告诉我如何执行此操作,我认为可以使用反射。但我没有这方面的知识。
答案 0 :(得分:5)
如果你真的不需要课,你可以使用反射或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);
}
一个有趣的替代方案是使用&#34;静态&#34;反射,如果你可以使用表达式而不是字符串 - 在你的情况下很可能没有用,但我想我可能会对比不同的方法。
// 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);
}
}
答案 1 :(得分:2)
您可以使用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");