【发布时间】:2015-05-19 13:47:57
【问题描述】:
我想为通用方法创建一个 Shim。但在那种情况下,我对 Generic 有点麻烦。
这是我的例子:
class BaseRepository <T> where T: Entity
{
public T[] FindAll()
{
return Method<T>.FindAll()
}
}
class ClassA : base<A>
{
}
class A : Entity
{
}
class ClassB : base<B>
{
}
class B : Entity
{
}
现在我想为 ClassA 和 ClassB 创建一个 ShimMethod
ShimBaseRepository<A>.AllInstances.FindAll = (repo) => MethodA();
ShimBaseRepository<B>.AllInstances.FindAll = (repo) => MethodB();
public A MethodA()
{
//Make the Same as MethodB
}
public B MethodB()
{
//Make the Same as MethodA
}
但是如果我有超过 20 个“基础”类怎么办?我不想为每个基类创建一个委托/方法。我尝试过这样的事情:
List<Type> allEntityClasses = (from x in Assembly.GetAssembly(typeof(Entity)).GetTypes()
where !x.IsAbstract && !x.IsInterface
select x).ToList();
foreach(Type type in allEntityClasses=
{
ShimBaseRepository<type????>.AllInstances.FindAll = (repo) => Method();
}
public Entity????? Method()
{
}
在我的单元测试中,我将使用以下方法:
ClassA.FindAll()
ClassB.FindAll()
而不是:
Base.FindAll()
编辑: 我使用 Microsoft Fakes,因此无法更改 ShimClass 中的任何内容。这是 Shim 生成的源代码。
public class ShimBaseRepository<T> : ShimBase<BaseRepository<T>> where T : Entity
{
public static class AllInstances
{
public static FakesDelegates.Func<BaseRepository<T>, T[]> FindAll { [ShimMethod("FindAll", 20)] set; }
}
}
我的意图是,我不想为每个实体创建一个委托,我只想遍历我的所有 EntityClasses 并动态创建委托。但我不知道如何在
中添加我的 Type 对象ShimBase<T>
【问题讨论】:
-
您要解决的问题是什么?您向我们展示了不起作用的解决方案,而不是您实际遇到的问题。另外,请确保您确实有可以运行的示例代码。