简体   繁体   中英

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

Cannot resolve symbol '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.

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:

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) .

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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