在我的项目中,我有以下的类结构:
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()
,第一个版本就可以正常工作。
那么是什么技术细节使通用版本在具体版本无法工作时起作用呢?