You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对ConcurrentDictionary的任意字段(Key或对象字段)排序并绑定GridView

问题原因与解决方法

你的核心问题是混淆了C#中的字段(Field)和属性(Property):

  • Detail类里的val1、val2等都是公共字段(语法为public int val1;)
  • Type.GetProperty()方法专门用于获取属性(语法为public int Val1 { get; set; }这种带访问器的成员),所以无论怎么调用都无法得到有效结果。

方案1:将字段改为属性(推荐)

这是.NET数据类的标准写法,更适配数据绑定和反射场景:

public class Detail
{
    public int Val1 { get; set; }
    public bool Val2 { get; set; }
    public DateTime Val3 { get; set; }
    public long Val4 { get; set; }
}

修改后,原代码里的Type.GetProperty(sortBy)就能正常获取PropertyInfo,排序逻辑可直接复用。


方案2:直接使用字段反射(不修改Detail类)

如果不想改动Detail类,可直接用FieldInfo获取字段值,调整排序逻辑:

private void LoadGridView(string sortBy = "Key")
{
    Type valType = typeof(Detail);
    FieldInfo fInfo = valType.GetField(sortBy);

    GridView1.DataSource = myDic.OrderBy(x => sortBy == "Key" 
        ? x.Key 
        : fInfo.GetValue(x.Value)
    ).ToList();

    GridView1.DataBind();
}

内容的提问来源于stack exchange,提问作者dwneder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 14:46:06