C# - 如何在不显式调用属性名

时间:2018-05-11 00:46:50

标签: c# .net dictionary

我有一个应用程序,其中我有一个具有100个属性值的类

例如。

Class RequestData{
 String PropertName1 {get;set;}
 String PropertName2 {get;set;}
 String PropertName3 {get;set;}
 .
 .
 .
 String PropertName100 {get;set;}
}

我有一个List>这有所有的propertyname和propertyvalues。所以,理想情况下这有

PropertName1 = "Timothy"
PropertName2 = "rajan"
.
.
.
PropertName100 = "alex"

我需要创建一个RequestData实例,并将所有属性值分配给每个属性名称

在这种情况下,我需要这样做,这将产生100行

 RequestData requestData = new RequestData ();
 requestData.PropertName1 = "Timothy" ;
 requestData.PropertName2 = "Rajan" ;
 requestData.PropertName3 = "Alex" ;

有更好的方法吗?我可以循环进入列表,但不知道如何巧妙地做到像

这样的事情
 RequestData requestData = new RequestData ();
 requestData.[key]= value ;

我希望我说清楚。任何帮助都会很棒。

3 个答案:

答案 0 :(得分:0)

你可以用反射来做到这一点

_list = new List<Tuple<string, string>>
   {
      new Tuple<string, string>("PropertName1", "asd"),
      new Tuple<string, string>("PropertName2", "sdfgds"),
      new Tuple<string, string>("PropertName3", "dfgdfg"),
      new Tuple<string, string>("PropertName100", "dfgdfg")
   };


var requestData = new RequestData();

foreach (var tuple in _list)
{
   requestData.GetType()
              .GetProperty(tuple.Item1, BindingFlags.Public| BindingFlags.NonPublic | BindingFlags.Instance )
             ?.SetValue(requestData, tuple.Item2);

}

或扩展方法

public void UpdateProperties<T>(this T obj, List<Tuple<string, string>> list) where T : class
{
   foreach (var tuple in _list)
   {
      var type = obj.GetType();
         var property = type.GetProperty(tuple.Item1, BindingFlags.Public| BindingFlags.NonPublic | BindingFlags.Instance );
      if(property == null)
         continue;
      property.SetValue(obj, tuple.Item2);
   }
}

Full Demo here

其他资源

Type.GetProperty Method (String)

  

搜索具有指定名称的公共属性。

PropertyInfo.SetValue Method (Object, Object)

  

设置指定对象的属性值。

BindingFlags Enumeration

  

指定控制绑定的标志以及搜索的方式   成员和类型是通过反思进行的。

答案 1 :(得分:0)

是的,你可以做到。没有更具体的细节,虽然很难给出一个好的&#34;响应。基于你所展示的内容(并且我可能做出了一个可能不好的假设),这里有几种可能的方法之一。我个人并不真的推荐这个,但也许它(带有其他答案/评论)会让你走上你真正想要/需要去的道路。

我应该提到有更有效的方法,但是想要展示一个基本的方法,对于实际发生的事情可能会更加明显。

    static void Main()
    {
        var propertyList = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("PropertyName1","Value1"),
            new KeyValuePair<string, string>("PropertyName2","Value2"),
            new KeyValuePair<string, string>("PropertyName3","Value3"),
            new KeyValuePair<string, string>("PropertyName4","Value4"),
            new KeyValuePair<string, string>("PropertyName5","Value5"),
        };

        var requestData = new RequestData();
        //reflection allows you to loop through the properties of a class
        foreach (var property in requestData.GetType().GetProperties())
        {
            //you can loop through your list (here I made an assumption that it's a list of KeyValuePair)
            foreach (var keyValuePair in propertyList)
            {
                //if the key matches the property name, assign the value
                if (property.Name.Equals(keyValuePair.Key))
                {
                    property.SetValue(requestData, keyValuePair.Value);
                }
            }
        }

        //to show that they are properly set
        Console.WriteLine(requestData.PropertyName1);
        Console.WriteLine(requestData.PropertyName2);
        Console.WriteLine(requestData.PropertyName3);
        Console.WriteLine(requestData.PropertyName4);
    }
}

public class RequestData
{
    public string PropertyName1 { get; set; }
    public string PropertyName2 { get; set; }
    public string PropertyName3 { get; set; }
    public string PropertyName4 { get; set; }
}

答案 2 :(得分:0)

在响铃中输入另一个类似的答案,这个使用字符串列表并在=符号上拆分,然后使用反射尝试获取属性名称,如果不是null,则设置属性我们的对象的价值:

private static void Main()
{
    var propNamesAndValues = new List<string>
    {
        "PropertName1 = Timothy",
        "PropertName2 = Rajan",
        "PropertName100 = Alex",
    };

    var requestData = new RequestData();

    foreach (var propNameValue in propNamesAndValues)
    {
        var parts = propNameValue.Split('=');
        if (parts.Length < 2) continue;

        var propName = parts[0].Trim();
        var propValue = parts[1].Trim();

        typeof(RequestData).GetProperty(propName)?.SetValue(requestData, propValue);
    }

    Console.WriteLine("{0} {1} {2}", requestData.PropertName1,
        requestData.PropertName2, requestData.PropertName100);

    GetKeyFromUser("\nDone! Press any key to exit...");
}

<强>输出

enter image description here