gpt4 book ai didi

c# - 在 C# 中,是否可以在运行时确定泛型的类型参数?

转载 作者:行者123 更新时间:2023-11-30 15:38:27 25 4
gpt4 key购买 nike

这是我所拥有的(使用 Rhino Mocks,但这不是问题的核心):

var entityMock = MockRepository.GenerateMock<IEntity>();
this.Cache = MockRepository.GenerateStub<Cache<IEntity>>();

是否可以更具体地设置Cache<T>的类型参数? ?像这样的东西:

var entityMock = MockRepository.GenerateMock<IEntity>();
this.Cache = MockRepository.GenerateStub<Cache<typeof(entityMock)>>();

这当然不能编译。但我想,如果可能的话,使用 Rhino Mocks 生成的类型,它是 IEntity 的具体实现。 .

最佳答案

可以使用反射在运行时创建一个封闭的通用类型。问题是您很可能不得不继续仅使用反射来操作它,因为(假定其类型在编译时未知)您不能将其键入为直接可用的东西。

例如,要创建“某物”的列表:

public IList CreateList(Type t)
{
var openListType = typeof(List<>);
return (IList)openListType.MakeGenericType(t);
}

这个例子说明了几个要点:

  1. 如果在编译时指定了“目标类型”,则不能这样做。换句话说,CreateList 不能接受 t 作为泛型类型参数并仍然允许相同的功能。
  2. 在最坏的情况下,新实例的类型只能是object。在这里,我们知道我们将始终创建一个 IList,因此情况要好一些。

我没有使用 Rhino Mocks 的经验,但在你的情况下它会转化为:

var entityMock = MockRepository.GenerateMock<IEntity>()
var cacheType = typeof(Cache<>).MakeGenericType(entityMock.GetType());
this.Cache = MockRepository.GenerateStub(cacheType);

...但仅当适当的GenerateStub 重载可用时。

关于c# - 在 C# 中,是否可以在运行时确定泛型的类型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11428465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com