使用提供的参数中指定的协变泛型类型调用方法
下面的 out
关键字(我不知道,但出于对您来说可能显而易见的原因)是不允许的:
public static class DataExtensions {
public static void ReplaceAll<T>(this EntityCollection<T> collectionToReplace, IEnumerable<T> collectionToAdd) where T : EntityObject {
RemoveEach(collectionToReplace);
foreach (T item in collectionToAdd) collectionToReplace.Add(item);
}
public static void RemoveEach(this EntityCollection<out EntityObject> collectionToEmpty) {
if (!collectionToEmpty.IsLoaded) collectionToEmpty.Load();
while (collectionToEmpty.Any()) collectionToEmpty.Remove(collectionToEmpty.First());
}
}
如果没有它,RemoveEach(collectionToReplace);
有一个参数不匹配:
参数 1:无法从“System.Data.Objects.DataClasses.EntityCollection
相同,当使用特定(非泛型)派生类型进行调用时。我必须使用以下签名吗?
public static void RemoveEach<T>(this EntityCollection<T> collectionToEmpty) where T : EntityObject {
如果是这样,智能感知或编译器应该警告我在此方法中使用抽象类作为通用类型说明符,因为我刚刚创建了一个不可调用的方法,不是吗?如果您不介意,请您指出为什么会这样(例如,如果允许的话,类型安全会被破坏或会导致混乱)。
谢谢你,香农
The out
keyword below is (as I didn't know, but for reasons that may be obvious to you) not allowed:
public static class DataExtensions {
public static void ReplaceAll<T>(this EntityCollection<T> collectionToReplace, IEnumerable<T> collectionToAdd) where T : EntityObject {
RemoveEach(collectionToReplace);
foreach (T item in collectionToAdd) collectionToReplace.Add(item);
}
public static void RemoveEach(this EntityCollection<out EntityObject> collectionToEmpty) {
if (!collectionToEmpty.IsLoaded) collectionToEmpty.Load();
while (collectionToEmpty.Any()) collectionToEmpty.Remove(collectionToEmpty.First());
}
}
and without it RemoveEach(collectionToReplace);
has a parameter mismatch:
Argument 1: cannot convert from 'System.Data.Objects.DataClasses.EntityCollection<T>' to 'System.Data.Objects.DataClasses.EntityCollection<System.Data.Objects.DataClasses.EntityObject>'
The same, when calling with a specific (non-generic) derived type. Do I have to do use the following signature?
public static void RemoveEach<T>(this EntityCollection<T> collectionToEmpty) where T : EntityObject {
If so, intellisense or the compiler should warn me about using an abstract class as the generic type-specifier in this method, because I've just created an un-callable method, no? And if you don't mind, would you please point out why this is so (e.g. a scenario where type-safety would be broken or confusion would result if it were allowed).
Thank you, Shannon
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该能够使用:
这是
EntityCollection
需要的唯一约束,并且您没有在方法主体中使用需要EntityObject
的任何内容。顺便问一下,您在这里所做的事情与调用
collectionToEmpty.Clear()
有很大不同吗?我已经有一段时间没有使用 EF 了,所以这并不完全明显......You should just be able to use:
That's the only constraint that
EntityCollection<T>
requires, and you're not using anything within the method body which needsEntityObject
.By the way, is what you're doing here very different to calling
collectionToEmpty.Clear()
? I haven't used EF for a while, so it's not entirely obvious...