Return input type of generic with type constraint in LINQ to Entities (EF4.1)

前端 未结 4 1393
春和景丽
春和景丽 2021-02-20 18:03

I have a simple extension method for filtering a LINQ IQueryable by tags. I\'m using this with LINQ to Entities with an interface of:

public interface ITaggable
         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-20 18:22

    You never show where this is used. I think you are already passing an IQueryable to the method in the first place.

    Proof of concept https://ideone.com/W8c66

    using System;
    using System.Linq;
    using System.Collections.Generic;
    
    public class Program
    {
        public interface ITaggable {}
    
        public struct TagStruct : ITaggable {}
        public class  TagObject : ITaggable {}
    
        public static IEnumerable DoSomething(IEnumerable input) 
            where T: ITaggable
        {
            foreach (var i in input) yield return i;
        }
    
        public static void Main(string[] args)
        {
            var structs = new [] { new TagStruct() };
            var objects = new [] { new TagObject() };
    
            Console.WriteLine(DoSomething(structs).First().GetType());
            Console.WriteLine(DoSomething(objects).First().GetType());               
        }
    }
    

    Output

    Program+TagStruct
    Program+TagObject
    

    So, it is returning the input type, not the constrained interface.

    Not surprising, what would have been the result if DoSometing required two interfaces?

        public static IEnumerable DoSomething(IEnumerable input) 
            where T: ITaggable, ISerializable
    

    ??

提交回复
热议问题