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

C#如何获取方法内object类型参数存储的类实例的各已设置属性值

问题原因

你之前的写法报错有两个核心原因:

  1. 你传入的forBothReservation是单个Reservation类实例,不是数组/集合,不需要加[0]索引取值
  2. 参数被声明为object类型,编译器不知道它的实际类型是Reservation,自然无法直接访问对应属性。

最优解决方案:用强类型参数

最推荐直接修改方法的参数类型,改成强类型Reservation,既能编译期校验,性能也最高:

// 修改参数类型为Reservation,不要再用object
public static async Task createReservation(Reservation forBothReservation, DataTable eachRoomNoOrHallName)
{
    string json = JsonConvert.SerializeObject(forBothReservation);
    StringContent data = new StringContent(json, Encoding.UTF8, "application/json");

    // 直接.访问属性即可
    var type = forBothReservation.type;
    var noDate = forBothReservation.no_date;
    var id = forBothReservation.id;
    // 其余属性同理直接读取
}

兼容方案:如果不能修改参数类型

如果这个方法需要兼容多种不同类型的入参,不能把参数改成Reservation,可以用类型判断转换的方式取值:

public static async Task createReservation(object forBothReservation, DataTable eachRoomNoOrHallName)
{
    string json = JsonConvert.SerializeObject(forBothReservation);
    StringContent data = new StringContent(json, Encoding.UTF8, "application/json");

    // 先判断类型匹配再转换取值
    if (forBothReservation is Reservation reservation)
    {
        var type = reservation.type;
        var noDate = reservation.no_date;
        var balance = reservation.balance;
        // 其余属性正常读取即可
    }
}

极端场景:动态读取未知类型属性

如果连入参的具体类型都不确定,需要通用读取属性,可以用反射实现:

public static async Task createReservation(object forBothReservation, DataTable eachRoomNoOrHallName)
{
    string json = JsonConvert.SerializeObject(forBothReservation);
    StringContent data = new StringContent(json, Encoding.UTF8, "application/json");

    Type objType = forBothReservation.GetType();
    // 读取type属性
    string type = objType.GetProperty("type")?.GetValue(forBothReservation) as string;
    // 读取no_date属性
    int? noDate = objType.GetProperty("no_date")?.GetValue(forBothReservation) as int?;
    // 其他属性按对应的类型转换即可
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 08:36:02