C# 迭代替换属性值的列表

C# 迭代替换属性值的列表,c#,C#,我如何遍历一个列表,用它的值替换每个属性名 以下是我到目前为止的情况,可能离这里很远:- public static string ReplaceText(List<Shared> list, string html) { foreach (PropertyInfo prop in list.GetType().GetProperties()) { html = html.Replace("list property n

我如何遍历一个列表,用它的值替换每个属性名

以下是我到目前为止的情况,可能离这里很远:-

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");
        }....
publicstaticstringreplacetext(列表,字符串html)
{
foreach(list.GetType().GetProperties()中的PropertyInfo属性)
{
html=html.Replace(“列表属性名称”、“列表属性值”);
}....

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

资料来源:

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

因此,您的问题实际上变成了“如何使用
PropertyInfo
获取给定对象实例的属性值?”,答案非常简单,“调用方法”

请参见下面的示例:

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;
}
演示中使用的类定义:

// 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; }
}

您的问题是什么?替换“列表属性名称”和“列表属性值”"对于列表中的数据,我的问题是您可能最好使用现有的模板库,例如或RazorEngine。对于初学者,我假定您对泛型列表类型的属性不感兴趣,而是对共享类型的属性感兴趣,是吗?在这方面,您需要从枚举共享对象开始然后枚举每个共享对象的属性。整个问题似乎还不成熟,因为你甚至还没有工作的想法。另外,你是想迭代列表还是列表对象的属性?就目前情况而言,你最好通过
对象而不是列表,因为你从来没有迭代过va列表中的lues。
// 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; }
}