简体   繁体   English

泛型方法不知道类型具有特定方法

[英]Generic method does not know that the type has a specific method

This does not compile: 这不会编译:

public ICollection<T> GetRelated<T>(Widget widget, IEnumerable<T> dbSet) where T : class
{
    return dbSet.Where(x => x.WidgetId == widget.WidgetId).ToList();
}

The red squiggly is at x.WidgetId and the error is 红色的波浪状在x.WidgetId ,错误为

Cannot resolve symbol 'WidgetId'. 无法解析符号“ WidgetId”。

All of the types I'll be using with this will be classes that have a WidgetId property, but the compiler doesn't know that. 我将使用的所有类型都是具有WidgetId属性的类,但是编译器并不知道。

I suspect that the only way to get this to work would be to create a base class or an interface that includes the WidgetId property (let's call it IMyBase ), have all of the appropriate classes derive from or implement that, then change this: 我怀疑使此工作正常进行的唯一方法是创建一个基类或包含WidgetId属性的接口(我们将其IMyBase ),让所有适当的类都派生自IMyBase或实现它,然后更改此方法:

where T : class

to this: 对此:

where T : IMyBase

Is there any other way to accomplish this? 还有其他方法可以做到这一点吗? Or is this a case of "that's what interfaces are for, so stop whining and start coding"? 还是这种情况是“那是接口的用途,所以请停止抱怨并开始编码”?

Try this approach: 试试这个方法:

public interface IWidgetId
{
    int WidgetId { get; }
}

public class Widget
{ 
}

public ICollection<T> GetRelated<T>(Widget widget, IEnumerable<T> dbSet) where T : IWidgetId
{
    return dbSet.Where(x => x.WidgetId == widget.WidgetId).ToList();
}

Use Enumerable.OfType(TResult) . 使用Enumerable.OfType(TResult)

It will filter out non-widgets but present the remaining widget elements as elements of widget type. 它将滤除非小部件,但将其余的小部件元素显示为小部件类型的元素。

return dbSet.OfType(Widget).Where(x => ……

But it is possibly better design to make your GetRelated method work only on ICollection<T> where T: Widget and use the OfType<Widget> filter external to it (ie, earlier in the pipeline). 但是,最好使GetRelated方法仅在ICollection<T> where T: Widget上起作用ICollection<T> where T: Widget并使用其外部的OfType<Widget>过滤器(即,管道中的早期版本)来设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM