【发布时间】:2017-02-15 15:13:33
【问题描述】:
我用谷歌搜索,但找不到满意的答案。我基本上是想让这段代码工作:
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>'
希望你能帮我解决这个问题。提前致谢
【问题讨论】:
-
我认为这作为一种方法有点毫无意义。如果您有 2 种类型,则有两种方法。
-
如果您对泛型类型进行类型检查,那么您几乎总是做出了糟糕的设计选择。
-
我会说它与类型变化有关——编译器不允许隐式转换为父类型。
-
好的,谢谢大家的回答。但是我看到很多人回复我写的具体功能。但是,此功能只是我要实现的基本版本。在最终版本中,我想根据 func 的转换设置一个更加复杂和动态的系统。所以每个人都可以忽略 if/else 语句的函数,只使用两种类型。谢谢