我不认为你可以将它作为一个类来做,目前,通常我在这种情况下尝试做的是创建最通用的类(采用最通用 args 的类)来拥有所有逻辑,然后制作更多特定的是默认这些类型的子类。
例如,假设我们正在编写一个翻译器,它将一种类型的值翻译成另一种类型,就像 aDictionary
但也有默认值等。
我们可以将其定义为:
public class Translator<TKey, TValue, TDictionary> where TDictionary : IDictionary<TKey, TValue>, new();
{
private IDictionary<TKey, TValue> _map = new TDictionary();
...
}
这是我的通用案例,它可以有任何实现IDictionary
,但是如果我们想要一个更简单的版本,Dictionary
如果没有指定,我们可以这样做:
public class Translator<TKey, TValue> : Translator<TKey, TValue, Dictionary<TKey, TValue>>
{
// all this does is pass on the "default" for TDictionary...
}
这样,我可以使:
// uses Dictionary<int, string>
var generic = new Translator<int, string>();
// uses SortedDictionary instead
var specific = new Translator<int, string, SortedDictioanry<int, string>>();
所以在你的情况下,也许你的泛型总是有一个 TValidator 属性,但它是默认的(也许总是true
以你最通用的形式返回?
例如,也许您有一个默认验证器的定义(例如称为DefaultValidator
),您可以反转您的定义,以便更通用(采用更多通用类型参数的那个)具有所有逻辑,并且任何专业化(更少的类型参数)只是默认这些额外类型的子类:
using System;
namespace SnippetTool.Repositories
{
public class DefaultValidator
{
// whatever your "default" validation is, may just return true...
}
public abstract class ARepository<TProvider> : ARepository<TProvider, DefaultValidator>
where TProvider : class
{
protected ARepository(TProvider provider) : base(provider, new DefaultValidator());
{
}
// needs no new logic, just any specialized constructors...
}
public abstract class ARepository<TProvider, TValidator>
where TProvider : class
where TValidator : class
{
public TValidator Validator { get; set; }
protected ARepository(TProvider provider, TValidator validator)
{
Provider = provider;
Validator = validator;
}
// all the logic goes here...
}
}
更新:是的,根据您的评论,如果它TValidator
是一个附加组件(而不是默认的东西),那么像您所做的那样分层是合适的。