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

如何在C#中将类类型存入变量并用于泛型方法调用?

解决方案

方法一:直接条件分支调用

这是最直观且性能最优的方式,适合当前仅两种类型的场景:

var mode = 1;
var repository = mode == 1 
    ? _unitOfWork.GetRepository<TestA>() 
    : _unitOfWork.GetRepository<TestB>();

方法二:反射动态调用泛型方法

如果后续需要支持更多类型,可通过反射实现动态选择:

var mode = 1;
Type targetType = mode == 1 ? typeof(TestA) : typeof(TestB);

// 获取GetRepository的泛型方法定义并指定类型
var method = _unitOfWork.GetType().GetMethod("GetRepository").MakeGenericMethod(targetType);
// 调用方法并获取结果
var repository = method.Invoke(_unitOfWork, null);

注意:反射性能略低于直接调用,非必要场景优先选方法一;另外需确保GetRepository是公开可访问的方法。

方法三:基于统一基类/接口的类型约束

如果TestA和TestB有共同业务逻辑,可让它们实现同一接口或继承同一基类,实现类型统一:
首先定义公共接口:

public interface ITestEntity {}
public class TestA : ITestEntity {}
public class TestB : ITestEntity {}

之后调用时可统一返回类型:

var mode = 1;
IRepository<ITestEntity> repository = mode == 1 
    ? _unitOfWork.GetRepository<TestA>() 
    : _unitOfWork.GetRepository<TestB>();

这里假设GetRepository<T>返回的IRepository<T>支持协变(即接口定义为IRepository<out T>),否则需根据实际情况调整返回类型。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 21:50:22