The type '' cannot be used as type paramet

2019-03-04 16:30发布

I have created this generic method

public IEnumerable<T> GetByID<T>(IEnumerable<T> source, int id) where T : IFields
{
   return source.Where(x => x.id == id);
}

where the IFieds interface is

public interface IFields
{
    string code { get; set; }
    int id { get; set; }
}

when i try to get the value, this obviously won't compile

DB.GetByID(Helper.Database.Table<Items>(), 1);

with the following compile error.

The type "Items" cannot be used as type parameter "T" in the generic type or method "DB.GetByID(System.Collections.Generic.IEnumerable, int)". There is no implicit reference conversion from "Items" to "IFields"

How can i fix that? Actually, i wish to use lambda expression "in an anonymous type".

1条回答
Luminary・发光体
2楼-- · 2019-03-04 16:38

The obvious reason for this error message is that Items doesn't implement IFields.

In other words, your Items type need to have this:

public class Items : IFields
                     ^-----^

If you don't have this, then Items is not a valid type for your GetByID<T> method since it doesn't implement this interface.

This is true even if the Items type just happens to have the right members. Unless you've explicitly stated that those members also implement the interface, by doing what I showed above, then that is not enough. So even if your Items type have the id property, you still have to state explicitly that the type implements the interface.

查看更多
登录 后发表回答