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

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

    You don't have to make the FilterMe method a generic method to achieve the same result.

        public class MyModel : IModel where T : MyObjectBase {
            public IQueryable GetRecords()
        {
            var entities = Repository.Query();
            if (typeof(IFilterable).IsAssignableFrom(typeof(T)))
            {
                //Filterme is a method that takes in IEnumerable
                entities = FilterMe(entities.Cast());
            }
            return entities;
        }
    
            public IEnumerable FilterMe(IEnumerable linked)  {
                var dict = GetDict();
                return linked
                        .Where(r => dict.ContainsKey(r.Id))
                        .Cast();
            }
        }
    

提交回复
热议问题