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

如何对C#类中通过反射获取的属性按名称排序?

按属性名称排序反射获取的PropertyInfo数组

你可以通过LINQ的OrderBy方法,基于PropertyInfo的Name属性对数组进行排序,具体实现如下:

  1. 确保代码文件顶部引入System.Linq命名空间(未引入的话需要添加):
using System.Linq;
  1. 修改获取属性数组的代码,在GetProperties()后链式调用排序方法:
MyClass md = new MyClass();

// 按属性名称升序排序
PropertyInfo[] properties = typeof(MyClass)
    .GetProperties()
    .OrderBy(p => p.Name)
    .ToArray();

foreach (PropertyInfo property in properties)
{
    double? d1 = /* 你的取值逻辑 */;

    if (property.PropertyType == typeof(double?))
    {
        if (property.GetValue(md) == null)
        {
            property.SetValue(md, d1);
        }
    }
}

如果需要按名称降序排序,只需将OrderBy替换为OrderByDescending:

PropertyInfo[] properties = typeof(MyClass)
    .GetProperties()
    .OrderByDescending(p => p.Name)
    .ToArray();

处理后,遍历属性时会按照属性名称的字母顺序(默认区分大小写)执行赋值操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 01:31:00