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

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

    In my answer, I assume that method FilterMe is used internally and should not be visible outside your model and could be marked private. If my assumption is wrong, you could create a private overload of FilterMe.

    In my answer I just removed the generic . I assume that this FilterMe always is about then entities of type T (since it is in the same Model class). This solves the problem about casting between T and TResult. TResult does not have to be marked as IFilterable since none of the members of IFilterable are used. And since the code already checks if T is IFilterable why check again (especially when FilterMe would be private)?

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

    If you would create a second FilterMe, replace the IEumerable types with Queryable, so you do not have to convert your entities with AsQueryable().

提交回复
热议问题