所以我们有这个:
public interface IWidget
{
int Id { get; set; }
}
public class Widget : IWidget
{
public int Id { get; set; }
}
public class WidgetProcessor
{
public static void ProcessWidgets1(IList<IWidget> widgets)
{ }
public static void ProcessWidgets2<T>(IList<T> widgets) where T : IWidget
{ }
}
Run Code Online (Sandbox Code Playgroud)
我明白为什么这不会编译:
WidgetProcessor.ProcessWidgets1(new List<Widget>());
C#规则围绕协方差明智地说它不应该,或者你可以得到各种各样的顽皮,正如其他地方详细解释的那样.
但是ProcessWidgets2:什么......?
它是如何,这确实编译和运行:
WidgetProcessor.ProcessWidgets2(new List<Widget>());
期待我的无知被删除,但我无法看到ProcessWidgets1和ProcessWidgets2(有效地)有何不同.
我有一系列办公室ID,数组可能为null.如果officeIdsToSelect数组为null,我希望EF查询返回所有记录,如果不是null,则返回匹配记录.不过这个:
int[] officeIdsToSelect = new int[] { 1, 2, 3 };
Office[] selectedOffices = (from item in new TdsDb().Offices
where (officeIdsToSelect == null || officeIdsToSelect.Contains(item.OfficeID))
select item).ToArray();
Run Code Online (Sandbox Code Playgroud)
抛出异常:
System.NotSupportedException : Cannot compare elements of type 'System.Int32[]'. Only primitive types (such as Int32, String, and Guid) and entity types are supported.
Run Code Online (Sandbox Code Playgroud)
特别是Linq to Entities反对officeIdsToSelect == null.我理解它的含义(一个更清晰的EF错误消息......)
那么我怎样才能得到我想要的东西呢?