首页 > 解决方案 > 如何从 C# 中传递的对象中检索单个值?

问题描述

在这种方法之前,我有一些方法包含四五个参数,所以我想将它们中的大部分压缩成一个对象。TestOptions() 对象具有附加的可选值,例如“名称”或“位置”。

我无法单独检索对象值。如何在 Setup() 方法中使用 TestOptions() 对象中的指定值?

    public async Task Test_One()
    {
        await Setup(new TestOptions() { brand = "Brand1", id = 10 }, new List<string> { "user1@abc.com" });
    }

    public async Task Setup(object values, List<string> emailAddresses)
    {
        //Do work here that uses 'brand' and 'id' individually
    }

public class TestOptions
{
    public string brand
    {
        get; set;
    }

    public string id
    {
        get; set;
    }
}

谢谢你。

标签: c#objectparameter-passingoptional-parameters

解决方案


您可以为Setup采用强类型对象进行签名:

public async Task Setup(TestOptions values, List<string> emailAddresses)
{
    //Do work here that uses 'brand' and 'id' individually
    var brand = values.brand;
}

或转换值:

public async Task Setup(object values, List<string> emailAddresses)
{
     //Do work here that uses 'brand' and 'id' individually
     var typed = (TestObject)values;
     var brand = typed .brand;
}

推荐阅读