更新仅知道其名称的对象的属性

Nic*_*ick 4 c#

我有一些定义如下的公共变量:

public class FieldsToMonitor
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int Rev {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

我现在想用值填充这些变量,但fm.[varible name]需求与相同field.Name。如果我提前知道属性名称和属性名称的顺序,这里将如何循环填充:

// loop 1
fm.Id = revision.Fields[field.Name].Value;

// ... loop 2 ...
fm.Title = revision.Fields[field.Name].Value;

// ... loop 3 ...
fm.Rev = revision.Fields[field.Name].Value;
Run Code Online (Sandbox Code Playgroud)

这是我想在哪里field.Name可以用属性名称代替的操作:

  • fm.ID变为fm。[field.Name],其中field.Name ==“ ID”

  • fm.Title变为fm。[field.Name]其中field.Name ==“ Title”

  • fm.Rev变为fm。[field.Name],其中field.Name ==“ Rev”

有解决方案吗?

这是到目前为止的更多代码:

public class FieldsToMonitor
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int Rev {get; set;}
}

static BindingList<FieldsToMonitor> FieldsToMonitorList
     = new BindingList<FieldsToMonitor>();
// ...

// Loop through the work item revisions
foreach (Revision revision in wi.Revisions)
{
    fm = new FieldsToMonitor();
    // Get values for the work item fields for each revision
    var row = dataTable.NewRow();
    foreach (Field field in wi.Fields)
    {
        fieldNameType = field.Name;
        switch (fieldNameType)
        {
            case "ID":
            case "Title":
            case "Rev":
                // the following doesn't work
                fm + ".[field.Name]" = revision.Fields[field.Name].Value; 
                fm[field.Name] = revision.Fields[field.Name].Value;
                row[field.Name] = revision.Fields[field.Name].Value;
                break;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

use*_*116 5

所有这些都在很大程度上取决于如何检索这些值,并且从有限的示例中很难判断这些值是字符串还是仅作为对象装箱的正确类型。

话虽如此,以下方法可能有效(但效率不高):

public static void SetValue<T>(T obj, string propertyName, object value)
{
    // these should be cached if possible
    Type type = typeof(T);
    PropertyInfo pi = type.GetProperty(propertyName);

    pi.SetValue(obj, Convert.ChangeType(value, pi.PropertyType), null);
}
Run Code Online (Sandbox Code Playgroud)

像这样使用:

SetValue(fm, field.Name, revision.Fields[field.Name].Value);
// or SetValue<FieldsToMonitor>(fm, ...);
Run Code Online (Sandbox Code Playgroud)


L.B*_*L.B 5

我不确定我是否正确理解您,但是可以尝试

public static class MyExtensions
{
    public static void SetProperty(this object obj, string propName, object value)
    {
        obj.GetType().GetProperty(propName).SetValue(obj, value, null);
    }
}
Run Code Online (Sandbox Code Playgroud)

用法像

Form f = new Form();
f.SetProperty("Text", "Form222");
Run Code Online (Sandbox Code Playgroud)