循环访问替换属性值的列表



我将如何遍历一个列表,将每个属性名称替换为其值?

以下是我到目前为止所拥有的,可能在这里很远:-

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");
        }....

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

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

重要的是要意识到GetProperties不是在对象本身上调用的,而是在对象Type上调用的。 该方法返回一个PropertyInfo对象的数组,其中仅包含有关属性定义的信息。

因此,您的问题实际上变成了"如何使用PropertyInfo来获取给定对象实例的属性值?",答案很简单"调用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; }
}

最新更新