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

前端 未结 8 1332
粉色の甜心
粉色の甜心 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:49
    public IEnumerable<TResult> FilterMe<TResult>(IEnumerable<TResult> linked) where TResult : IFilterable
    {
        var dict = GetDict();
        return linked.Where(r => dict.ContainsKey(r.Id));
    }
    

    Try replacing FilterMe with this version:

    public IEnumerable<T> FilterMe(IEnumerable<IFilterable> linked)
    {
        var dict = GetDict();
        return linked.Where(r => dict.ContainsKey(r.Id)).Cast<T>();
    }
    

    Then, were you call, change your code to this:

    if (typeof(IFilterable).IsAssignableFrom(typeof(T)))
    {
        //Filterme is a method that takes in IEnumerable<IFilterable>
        var filterable = entities.Cast<IFilterable>();
        entities = FilterMe(entities).AsQueryable();
    }
    
    0 讨论(0)
  • 2021-02-05 11:50
    if (typeof(IMyInterface).IsAssignableFrom(typeof(T))
    

    This checks whether a variable of type IMyInterface can be assigned from an instance of type T.

    0 讨论(0)
提交回复
热议问题