C#: specialized template method - Error: Type '…' already defines a member called '…' with the same parameter types

前端 未结 2 1381
-上瘾入骨i
-上瘾入骨i 2021-01-23 13:02

I\'m quite new to C# and currently developing an application using the EntityFramework. I would like to extend the functionality of the database context class, so that I can cal

2条回答
  •  伪装坚强ぢ
    2021-01-23 13:40

    Unfortunately, in C#, you cannot overload a method by using a generic type constraint like this. You will have to give them different names like this

    public class TestContext : DbContext
    {
        public DbSet ATests { get; set; }
        public DbSet BTests { get; set; }
    
        public IQueryable getPoolA() where T : TestA {
           return (IQueryable)ATests;
        }
        public IQueryable getPoolB() where T : TestB {
           return (IQueryable)BTests;
        }
    }
    

    Another solution would be to do something like this:

    public class TestContext : DbContext
    {
        public DbSet ATests { get; set; }
        public DbSet BTests { get; set; }
    
        public IQueryable getPool() {
           return (typeof(T) == typeof(TestA))
                      ? (IQueryable)ATests
                      : (IQueryable)BTests;
        }
    }
    

    Now, you can make this even cleaner, since IQueryable is covariant in T, you can avoid casting:

    public class TestContext : DbContext
    {
        public DbSet ATests { get; set; }
        public DbSet BTests { get; set; }
    
        public IQueryable getPool() {
           return (typeof(T) == typeof(TestA)) ? ATests : BTests;
        }
    }
    

    If you want to avoid testing for types you can do something like this:

    public class TestContext : DbContext
    {
        readonly Dictionary _sets;
    
        public DbSet ATests { get; set; }
        public DbSet BTests { get; set; }
    
        public TestContext()
        {
            _sets = new Dictionary
            {
                { typeof(TestA), ATests },
                { typeof(TestB), BTests }
            }
        }
    
        public IQueryable getPool() {
           return (IQueryable)_sets[typeof(T)];
        }
    }
    

提交回复
热议问题