【问题标题】:In C#, Generically get the property value within a List object在 C# 中,通常获取 List 对象中的属性值
【发布时间】:2018-10-27 02:47:35
【问题描述】:

我有一个结构为的 Match 对象,

class Match
{
    public string location { get; set; }
    public List<Team> teams { get; set; }
    public Match()
    {
        location = "Wembley";
        teams = new List<Team>();
        teams.Add(new Team("Arsenal"));
        teams.Add(new Team("Burnley"));
    }
}
public class Team
{
    public string name { get; set; }
    public int score { get; set; }
    public Team(string title)
    {
        name = title;
        score = 0;
    }
}

我使用辅助类来获取值,

public static class Helper
    {
        public static object GetPropertyValue(this object T, string PropName)
        {
            return T.GetType().GetProperty(PropName) == null ? null :  T.GetType().GetProperty(PropName).GetValue(T, null);
        }
    }

我计划允许用户通过在 GUI 中键入值来设置值,例如“match.team[1].name”,然后将其拆分为参数调用,例如在此代码中;这可能会下降几层。这里我们下一层从列表的一个成员中获取一个属性值,

int teamNo = 1;
MessageBox.Show(GetSubProperty(match, "teams", teamNo, "name")); 

我的日常是这样的,

    private string GetSubProperty(object obj, string prop1, int whichItem,  string prop2)
    {
        var o = obj.GetPropertyValue(prop1);
        object subObject = ((List<Team>)o)[whichItem];
        return subObject.GetPropertyValue(prop2).ToString();
    }

在获取 Team List 对象之一的属性时,我必须先将值转换为 List,然后才能访问列表中的单个项目。我想知道如何为发送的任何对象类型一般地执行此操作。我尝试了 List 和 ArrayList 以及许多其他变体,但出现错误“无法转换类型为‘System.Collections.Generic.List@’的对象987654325@1[System.Object]"

【问题讨论】:

  • 是否有必要以这种方式向用户公开您的对象布局并期望他们知道这一点?为什么不只是有一个 UI 允许他们只设置团队名称等而不绑定到您的班级布局。
  • 您使用的是什么 UI 框架?如果是 Winforms 或 WPF,那么它们都具有强大的数据绑定机制,更适合这种对象数据更新
  • 有效积分,谢谢,但是虽然后端是C#,但前端可能不是。我可以对模型进行反思,为用户提供数据结构,然后他们可以将该数据定向到其他流。
  • 查看我关于数据绑定的第二条评论

标签: c# list object reflection


【解决方案1】:

使用 IEnumerable。这似乎有效:

private string GetSubProperty(object obj, string prop1, int whichItem, string prop2)
{
    var o = obj.GetPropertyValue(prop1);

    int count = 0;
    foreach (object subObject in (IEnumerable)o)
    {
        if (whichItem == count++)
        {
            return subObject.GetPropertyValue(prop2).ToString();
        }
    }

    return null;
}

当然,请务必检查此演员阵容是否有效。您可以通过尝试转换为各种事物并根据 o 的类型执行适当的代码来使您的解决方案更加通用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    相关资源
    最近更新 更多