1 c# reflection
IDE:Visual Studio 2010,C#,.NET 4.0,Winforms应用程序.在我开始之前看到这个课程:
public class Car
{
private string _break;
public string Break
{
get { return _break; }
set { _break = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
我有另一堂课:
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?
}
Run Code Online (Sandbox Code Playgroud)
我有字符串格式的属性名称,我想在属性中转换它,并希望初始化它.请告诉我如何执行此操作,我认为可以使用反射.但我没有那种知识.
如果你真的不需要类,可以使用反射或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);
}
Run Code Online (Sandbox Code Playgroud)
一个总是有趣的替代方案是使用"静态"反射,如果你可以使用表达式而不是字符串 - 在你的情况下很可能不必要,但我想我可能会对比不同的方法.
// 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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
179 次 |
| 最近记录: |