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

如何在C#的Nullable<object>实例中访问成员变量?

解决匿名对象赋值给object?后的成员访问问题

你把匿名对象赋值给object?类型变量后,编译时编译器只识别它为object类型,自然没法直接访问匿名成员,智能提示也无法生效。下面是几种可行的解决办法:

方法1:使用类型模式匹配(推荐,类型安全)

利用C#的类型模式匹配,直接捕获匿名对象的成员,同时保留编译时类型检查:

public class TestEntity
{
    public int TestMethod()
    {
        var someObject = new
        {
            info_id = "TestItOutInfoId",
            customer_email_address = "lin@newyork.com", // 原代码漏了字符串引号,需修正
            subject = "Resolved",
            sent_date_time = DateTime.Now,
            sender_email_address = "mac@don.com" // 同样需加引号
        };

        // 方式1:直接解构需要的成员
        if (someObject is { info_id: string infoId, customer_email_address: string customerEmail })
        {
            // 使用解构后的变量
            Console.WriteLine(infoId);
            Console.WriteLine(customerEmail);
            // 其他成员可按需添加到花括号中
        }

        // 方式2:直接匹配匿名类型(同一程序集内匿名类型结构一致则为同一类型)
        if (someObject is var anonObj)
        {
            Console.WriteLine(anonObj.info_id);
            Console.WriteLine(anonObj.customer_email_address);
        }

        return 0;
    }
}

方法2:改用dynamic类型

将变量声明为dynamic,绕过编译时类型检查,直接在运行时访问成员:

public class TestEntity
{
    public int TestMethod()
    {
        dynamic someObject = new
        {
            info_id = "TestItOutInfoId",
            customer_email_address = "lin@newyork.com",
            subject = "Resolved",
            sent_date_time = DateTime.Now,
            sender_email_address = "mac@don.com"
        };

        // 直接访问成员
        string infoId = someObject.info_id;
        string customerEmail = someObject.customer_email_address;

        return 0;
    }
}

注意:这种方式没有编译时校验,成员名拼写错误会导致运行时异常

方法3:定义强类型类(最推荐,便于长期维护)

如果这个对象的结构是固定的,直接定义对应的实体类替换匿名对象,既能享受智能提示,又能保证类型安全:

// 定义对应实体类
public class EmailInfo
{
    public string info_id { get; set; }
    public string customer_email_address { get; set; }
    public string subject { get; set; }
    public DateTime sent_date_time { get; set; }
    public string sender_email_address { get; set; }
}

public class TestEntity
{
    public int TestMethod()
    {
        EmailInfo someObject = new EmailInfo
        {
            info_id = "TestItOutInfoId",
            customer_email_address = "lin@newyork.com",
            subject = "Resolved",
            sent_date_time = DateTime.Now,
            sender_email_address = "mac@don.com"
        };

        // 直接访问成员,智能提示正常生效
        string infoId = someObject.info_id;
        string customerEmail = someObject.customer_email_address;

        return 0;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 12:17:10