In C# how can i check if T is of type IInterface and cast to that if my object supports that interface?

前端 未结 8 1348
粉色の甜心
粉色の甜心 2021-02-05 10:52

In C#, I have a function that passes in T using generics and I want to run a check to see if T is an object that implements a

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-05 11:44

    The simplest form I can come up with is something like:

    public IEnumerable GetRecords()
    {
        IQueryable entities = new List().AsQueryable();
    
        if (typeof(IFilterable).IsAssignableFrom(typeof(T)))
        {
            entities = FilterMe(entities.OfType()).AsQueryable();
        }
    
        return entities;
    }
    
    public IEnumerable FilterMe(IEnumerable linked) where TSource : IFilterable
    {
        return linked.Where(r => true).OfType();
    }
    

    The point here is the need to have types to pass into and get back out of the method. I had to change the types locally to get it working.

    OfType will silently filter out items that are not really of a given type, so it assumes that it's a collection of the same type in any one call.

    Because you are re-assigning from FilterMe, you still need the interface assignable check.

提交回复
热议问题