继承通用不变性C#4

时间:2013-03-01 09:25:46

标签: c#-4.0 generics inheritance instance variance

我一直在寻找为什么这个通用结构不能编译

我明白了:
无法将类型'WpfApplication1.CowDao'隐式转换为'WpfApplication1.Dao'

public abstract class Animal { }

public class Dog : Animal { }

public class Cow : Animal { }

public abstract class Dao<T> where T : Animal 
{
    public void Insert(T t);
}

public class DogDao : Dao<Dog> { }

public class CowDao : Dao<Cow> { }

public class Main
{
    public Main()
    { 
        Dao<Animal> dao = null;

        if (true) dao = new DogDao();
        else dao = new CowDao();
    }
}

我只想达到目标 - &gt;制作一个“中立”的实例 我认为我的建设必须改变,但我不知道如何

我正在使用.NET Framework 4

由于

2 个答案:

答案 0 :(得分:0)

将Dao图层的继承更改为

public class DogDao : Dao<Animal> { }

public class CowDao : Dao<Animal> { }

编辑:

 public abstract class Dao<T> where T : Animal
    {
        public virtual void Insert(T t)
        {

        }

        protected void ExecuteQuery(string quer)
        {

        }
    }

    public class DogDao : Dao<Dog>
    {
        public override void Insert(Dog t)
        {
            string insert = "INSERT INTO DOG ...";

            base.ExecuteQuery(insert);
        }
    }

    public class CowDao : Dao<Cow>
    {
        public override void Insert(Cow t)
        {
            string insert = "INSERT INTO COW ...";

            base.ExecuteQuery(insert);
        }

    }

答案 1 :(得分:0)

派生的泛型不会从基类继承Generic,因此您不能将它们转换为另一个。相反,编写一个扩展方法ToGenericParent,其转换如下:

public static Generic<Parent> ToGenericParent(this Generic<Derived> derived)
        {
            return new Generic<Parent>() { Value = derived.Value };
        }