为什么此扩展方法适用于泛型而不是设置基类型
本文关键字:设置 基类 类型 泛型 扩展 方法 适用于 为什么 | 更新日期: 2023-09-27 18:36:30
在我的项目中,我有以下类结构:
public interface IUpdateableModel
{
ModelState State { get; set; }
void ResetState();
}
public abstract class UpdateableModel : IUpdateableModel
{
public ModelState State { get; set; }
public void ResetState()
{
//Perform reset logic
}
}
public class MyUpdateableClass : UpdateableModel
{
//Some properties.
}
现在我正在尝试添加一些扩展方法以用于IUpdateable
集合:
public static class UpdateableModelExtensions
{
public static bool HasUnsavedChanges(this IList<IUpdateableModel> collection)
{
return collection.Any(x => x.State != ModelState.Unmodified);
}
public static void ResetItemStates<T>(this IList<T> collection) where T : IUpdateableModel
{
var itemsToRemove = collection.Where(x => x.State == ModelState.New).ToList();
foreach (var item in itemsToRemove)
{
collection.Remove(item);
}
var itemsToAdd = collection.Where(x => x.State == ModelState.Deleted).ToList();
foreach (var item in itemsToAdd)
{
item.State = ModelState.Unmodified;
}
var itemsToReset = collection.Where(x => x.State == ModelState.Modified).ToList();
foreach (var item in itemsToReset)
{
item.ResetState();
}
}
}
如在List<MyUpdateableClass>
上使用它时所写,会产生一个编译器错误,即类型不匹配。
public class MyClass
{
public IList<MyUpdateableClass> Items {get; set;}
public void MyMethod()
{
if(Items.HasUnsavedChanges()) //Compiler error
{
//Do some stuff
}
}
}
编译器错误为:
'IList<MyUpdateableModel>' does not contain a definition for
'HasUnsavedChanges' and the best extension method overload
'UpdateableModelExtensions.HasUnsavedChanges(IList<IUpdateableModel>)'
requires a receiver of type 'IList<IUpdateableModel>'
如果将扩展方法更改为 IList<UpdateableModel>
但是,如果我改用泛型来实现这一点,它可以正常工作:
public static bool HasUnsavedChanged<T>(this IList<T> collection)
where T : IUpdateableModel
{
return collection.Any(x => x.State != ModelState.Unmodified);
}
此外,如果我将用法更改为Items.Cast<IUpdateableModel>().ToList()
第一个版本确实有效。
具体版本不起作用时,允许通用版本工作的技术细节是什么?
这是因为 IList 内容比签名允许的更具体。这可能导致违反默示合同。
IList<IUpdateableModel>
的合同是,IUpdateableModel
的任何实施者都必须能够添加到列表中。这对于List<ImplementationOfUpdateableModel>
是不可能的,因为您只能添加类型为 ImplementationOfUpdateableModel
的对象。
泛型版本之所以有效,是因为它允许该方法接受更具体对象内容的 IList。