我google了,但无法找到满意的答案。我基本上试图让这个代码工作:C#转换System.Func <Tderived,布尔>到系统/功能<Tbase, bool>
public List<WordEntry> WordDataBase = new List<WordEntry>();
public List<CharacterEntry> CharacterDataBase = new List<CharacterEntry>();
public List<Entry> SelectWhere<T>(System.Func<T, bool> predicate) where T : Entry
{
if (typeof(T) == typeof(WordEntry))
return WordDataBase.Where(predicate);
else if (typeof(T) == typeof(CharacterEntry))
return CharacterDataBase.Where(predicate);
else
return null;
}
在这个示例中,WordEntry和CharacterEntry都从Entry派生。我得到的编译器错误:
Error CS1503 Argument 2: cannot convert from 'System.Func<T, bool>' to 'System.Func<WordEntry, int, bool>'
和
Error CS1503 Argument 2: cannot convert from 'System.Func<T, bool>' to 'System.Func<CharacterEntry, int, bool>'
希望你能帮助我与此有关。在此先感谢
我认为这是一种毫无意义的方法。如果你有两种类型,那么有两种方法。 –
如果您正在对泛型进行类型检查,那么您几乎总是做出糟糕的设计选择。 – juharr
我会说它与类型差异有关 - 编译器不允许隐式转换为父类型。 – gobes