c# - 如何从 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;
}
}
谢谢你。
解决方案
您可以为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;
}
推荐阅读
- php - 将代码从 while 循环更改为 array_shift
- oracle - 如果使用 group by 子句没有行返回,则 select 语句应将计数返回为零
- javascript - 通过innerHTML查找元素以从注入的javascript调用角度ng-click
- azure - 我可以获取“正在更新”的 Service Fabric 群集的状态/信息吗?
- android - android布局中的多屏幕支持
- azure-devops - 使用权限/其他功能来限制 Azure DevOps 中的部署
- shell - 如何在 shell 中一次删除目录及其后代?
- json - 我尝试将此 cURL 代码转换为 Retrofit2 的代码,但我不能
- eclipse - 无法添加 JUnit 5 测试用例
- c# - C# Linq 数据表 groupby 日期时间月