我们有一个泛型类,它包含一个使用外部类的泛型类型参数的私有(private)类。例子:
public class Foo<T>
{
private class Bar : IGrouping<Guid,T>{
}
}
问题是我们在一个单元测试项目中得到一个编译错误,它指出
"The Type or method has 2 generic parameter(s), but 1 generic argument(s) were provided. A generic argument must be provided for each generic parameter."我提高了 MSBuild 的详细程度(工具 > 选项 > 项目和解决方案 > 构建和运行)。查看错误位置,它指向 Microsoft.TeamTest.targets 文件。我能够将其缩小到上面的这个类结构。如果我用类定义中的具体泛型参数替换私有(private)类 Bar(见下文),则单元测试编译得很好:
private class Bar : IGrouping<Guid,int>{
}
我需要提供第二个泛型参数 generic 来接受外部类中的任何类型。对这个有想法吗?
为了澄清,编译错误在单元测试项目中,而不是上面列出的代码(编译得很好)。也许私有(private)访问器生成在 MS 单元测试基础架构中令人窒息?
这是[几乎]整个实际代码:
public class CategoryStorageService<T> : StorageServiceBase<T>, ICategoryStorageService<T> where T : IStorageContent, new()
{
/// <summary>
/// Returns a nested object graph of category-items
/// </summary>
/// <param name="categories"></param>
/// <returns></returns>
public IEnumerable<IGrouping<StorageCategory, T>> GetContent(params StorageCategory[] categories)
{
var results = this.GetContent(categories.Select(c => c.ID).ToArray());
foreach (var result in results)
{
yield return new LocalNameGrouping(
categories.First(c => c.ID == result.Key.ID),
result);
}
}
/// <summary>
/// Returns a nested object graph of categories, each containing their items
/// </summary>
/// <param name="categories">The ID(s) of the category(ies) to fetch</param>
/// <returns></returns>
private IEnumerable<IGrouping<StorageCategory, T>> GetContent(params Guid[] categories)
{
// implementation removed
return null;
}
private class LocalNameGrouping : IGrouping<StorageCategory, T>
{
private IEnumerable<T> items;
private StorageCategory category;
public LocalNameGrouping(StorageCategory localCategory, IGrouping<StorageCategory, T> items)
{
this.items = items;
string name = string.IsNullOrEmpty(localCategory.DisplayName) ? items.Key.DisplayName : localCategory.DisplayName;
this.category = new StorageCategory { DisplayName = name, ID = items.Key.ID };
}
#region IGrouping<StorageCategory,T> Members
public StorageCategory Key
{
get { return category; }
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
return items.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
}
最佳答案
因此,私有(private)访问器处理对部分构造了泛型类定义的类型感到愤怒。例如,如果类声明如下:
private class LocalNameGrouping : IGrouping<StorageCategory, T> {
}
然而,它对此很满意,仍然满足了需求(尽管有点俗气):
private class LocalNameGrouping<K> : IGrouping<K, T> where K: StorageCategory, new()
{
}
关于.Net 单元测试编译错误 - 类型或方法有 2 个通用参数,但提供了 1 个通用参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3158408/