迭代替换属性值的列表

时间:2016-02-10 17:04:54

标签: c#

如何迭代列表,用其值替换每个属性名称?

以下是我到目前为止的情况,可以在这里: -

public static string ReplaceText(List<Shared> list, string html)
    {
        foreach (PropertyInfo prop in list.GetType().GetProperties())
        {
            html = html.Replace("list property name", "list property value");
        }....

2 个答案:

答案 0 :(得分:2)

您必须使用prop.Name获取属性的名称,并使用prop.GetValue(object obj)获取值..

来源: https://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo(v=vs.110).aspx

答案 1 :(得分:1)

认识到GetProperties在对象本身上被称为而不是,而不是Type,这一点非常重要。该方法返回PropertyInfo个对象的数组,该数组仅包含有关属性定义的信息。

所以你的问题实际上变成了#34;我如何使用PropertyInfo获取给定对象实例的属性值?&#34;,答案很简单&#34 ;调用PropertyInfo.GetValue(Object)方法。

见下面的例子:

public Dictionary<String, String> GetPropertyValues<T>(T obj)
{
    Dictionary<String, String> result = new Dictionary<String, String>();
    var properties = obj.GetType().GetProperties();
    foreach (var property in properties)
    {
        String name = property.Name;
        String value = property.GetValue(obj).ToString();
        result.Add(name, value);
    }
    return result;
}

用法:

MyClass myClass = new MyClass { PropertyName = "Testing 1, 2, 3" };

String template = "The value of PropertyName is '{PropertyName}'";
var replacements = GetPropertyValues(myClass);
foreach (var replacement in replacements)
{
    // Note that you have to double-up the '{' and '}' characters to escape them.
    String token = String.Format("{{{0}}}", replacement.Key);
    Console.WriteLine("Searching for occurrences of '{0}'", token);
    template = template.Replace(token, replacement.Value);
}

Console.WriteLine(template);
// Output:
// The value of PropertyName is 'Testing 1, 2, 3'   

演示中使用的类定义:

// A simple class definition for demonstration purposes.
// The method is generic, so as to work reasonably well for general purposes.
public class MyClass
{
    public String PropertyName { get; set; }
}