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

前端 未结 8 1343
粉色の甜心
粉色の甜心 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:45

    The missing piece is Cast<>():

    if(typeof(IFilterable).IsAssignableFrom(typeof(T))) {
        entities = FilterMe(entities.Cast()).AsQueryable().Cast();
    }
    

    Note the use of Cast<>() to convert the entities list to the correct subtype. This cast would fail unless T implements IFilterable, but since we already checked that, we know that it will.

提交回复
热议问题