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

C#如何在一行代码中实例化对象、调用方法并赋值两个变量?

一行代码同时实例化DAO并获取Device的通用方案

方案1:泛型工具方法(通用且避免重复实例化)

先定义一个通用的泛型静态类,封装「创建实例+执行操作+返回实例与结果」的逻辑:

public static class InstanceHelper
{
    public static (TInstance, TResult) CreateAndExecute<TInstance, TResult>(Func<TInstance, TResult> action) 
        where TInstance : new()
    {
        var instance = new TInstance();
        var result = action(instance);
        return (instance, result);
    }
}

调用时一行代码完成两个变量的赋值:

var (dao, device) = InstanceHelper.CreateAndExecute((DeviceCommunicationDao dao) => dao.GetDeviceById(123));

借助C#类型推断,还可以简化为:

var (dao, device) = InstanceHelper.CreateAndExecute<DeviceCommunicationDao, Device>(d => d.GetDeviceById(123));

方案2:元组解构(简单但会重复实例化)

如果不介意重复创建DeviceCommunicationDao实例,可直接用元组解构实现一行赋值:

var (dao, device) = (new DeviceCommunicationDao(), new DeviceCommunicationDao().GetDeviceById(123));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 01:32:00