【问题标题】:How to set a property of an object which name is in string form? [duplicate]如何设置名称为字符串形式的对象的属性? [复制]
【发布时间】:2014-07-18 00:47:13
【问题描述】:

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?
}

我有字符串格式的属性名称,我想将其转换为属性并初始化它。请告诉我如何执行此操作,我认为可以使用反射。但我没有这方面的知识。

【问题讨论】:

  • 正确的术语是反射。你想做的事情相当容易;只是一些陈述。首先了解如何从对象中检索属性,然后了解如何为检索到的属性设置值。
  • 我有字符串格式的属性名称,即“Break”,我想在 obj.Break 中转换它,这样我就可以给它赋值。这只是一个例子,我必须使用它我的应用程序中的概念
  • @Jeroen Vannevel,我知道它的反射,拼写错误。但如果你能说出解决方案而不是发现拼写错误,那就更好了。
  • 我确实给了你解决方案;我只是告诉你该怎么做而不是给你代码(这是 2 行)。如果您希望代码没有任何尝试,请查看链接的副本。

标签: c# reflection


【解决方案1】:

如果您真的不需要类,您可以使用反射或 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);
    } 
}

【讨论】:

【解决方案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");

【讨论】:

    猜你喜欢
    • 2012-11-16
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多