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

C#中如何访问List内的类对象并按传入属性名字符串动态取值打印

问题原因

你当前写法报错是因为C#为静态编译语言,无法直接将字符串拼接在对象访问符.后作为属性名使用,编译阶段无法识别这种动态拼接的成员路径。
另外注意一个前置bug:你定义的Sample类中地址属性拼写为adress(缺失字母d),但CSV赋值时使用的是address,请先统一修正为address,否则会直接触发编译错误。


解决方案1:分支判断(最适合新手)

你当前只有3个属性,直接用switch分支匹配属性名即可,逻辑简单、性能高,无需额外技术:

private static void PrintSample(Sample getData, string whatData)
{
    string result = whatData switch
    {
        "name" => getData.name,
        "phone" => getData.phone,
        "address" => getData.address,
        _ => "未知属性"
    };
    Console.WriteLine(result);
}

解决方案2:反射实现动态获取(适合属性多的场景)

如果后续属性数量多,不想写大量分支,可以用C#的反射机制动态根据属性名取值:

private static void PrintSample(Sample getData, string whatData)
{
    // 获取Sample类型的元数据
    var type = typeof(Sample);
    // 查找对应名称的属性
    var property = type.GetProperty(whatData);
    if (property == null)
    {
        Console.WriteLine($"不存在名为{whatData}的属性");
        return;
    }
    // 从getData实例中获取该属性的值
    var value = property.GetValue(getData)?.ToString() ?? "空值";
    Console.WriteLine(value);
}

可选优化

为了避免传入属性名时拼写错误,可以将允许的属性名定义为枚举,替换字符串参数:

public enum SampleProperty
{
    Name,
    Phone,
    Address
}
// 调用时改为
PrintSample(getData, SampleProperty.Name);
// 方法内匹配枚举即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:15:08