使此方法具有可变参数泛型

时间:2019-01-21 17:37:52

标签: c#

是否有任何使该方法通用的创造性方法,我讨厌不得不将其复制粘贴到任何地方:

private CoachContext GetMockContext(Mock<DbSet<LastViewedRecord>> mockSet) {
  var autoFixture = new Fixture();
  DbContextOptions<CoachContext> options = autoFixture
    .Build<DbContextOptions<CoachContext>>()
    .Create();
  var mockContext = new Mock<CoachContext>(options);
  mockContext.Setup(c => c.LastViewedRecords).Returns(mockSet.Object);
  return mockContext.Object;
}

我可以将LastViewedRecord改成T并使方法通用,但是我无法绕过c => c.LastViewedRecords

解决方案:,我将方法签名更改为以下形式:

protected CreditCoachContext GetMockContext<T>(
  IQueryable<T> mockData,
  Expression<Func<CreditCoachContext,
  DbSet<T>>> contextExpression
) where T : class

1 个答案:

答案 0 :(得分:1)

类似的东西可能会有所帮助。 (PS:我不确定Fixture

private TReturn GetMockContext<TContext, TEntity, TReturn>(Mock<DbSet<TEntity>> mockSet, 
  Expression<Func<CreditCoachContext>> contextExpression) 
    where TContext : DbContext, new() 
    where TEntity : class 
    where TReturn : class
{
  var autoFixture = new Fixture();
  DbContextOptions<TContext> options = autoFixture
    .Build<DbContextOptions<TContext>>()
    .Create();
  var mockContext = new Mock<TContext>(options);
  mockContext.Setup(contextExpression).Returns(mockSet.Object);
  return mockContext.Object;
}