我想知道为什么下面的泛型方法不能编译(C# 4.0)。我的同事和我都无法弄清楚。
编译器抱怨this
which is aSelectableRowBase
不能转换为 a TItem
,它被限制为从SelectableRowBase
. 如果我进行显式转换,一切正常(这就是我在源代码管理中检查的内容),但我想知道编译器为什么在这里抱怨。
那是编译器错误吗?我错过了什么吗?
public class SelectableRowBase
{
public void AddToSelectedListWhenIsSelectedChanges<TItem>
(ObservableCollection<TItem> selectedList)
where TItem : SelectableRowBase
{
// Causes error:
// The best overloaded method match for
// 'System.Collections.ObjectModel.Collection<TItem>.Add(TItem)'
// has some invalid arguments
// Argument 1: cannot convert from SelectableRowBase' to 'TItem'
Action actionOnSelected = () => selectedList.Add(this);
Action actionOnDeselected = () => selectedList.Remove(this);
// Compiles and works fine
// only difference is the explicit cast
Action actionOnSelected = () => selectedList.Add((TItem)this);
Action actionOnDeselected = () => selectedList.Remove((TItem)this);
}
}