1

この一般的な構造がコンパイルされない理由を探していました

取得:
タイプ「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();
    }
}

目標を達成したいだけです->「ニュートラル」インスタンス
を作成する構造を変更する必要があると思いますが、方法がわかりません

.NETFramework4を使用しています

ありがとう

4

2 に答える 2

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);
        }

    }
于 2013-03-01T09:29:34.883 に答える
0

派生クラスのジェネリックは、基本クラスのジェネリックを継承しないため、別のクラスにキャストすることはできません。代わりに、次のように変換する拡張メソッド ToGenericParent を記述します。

public static Generic<Parent> ToGenericParent(this Generic<Derived> derived)
        {
            return new Generic<Parent>() { Value = derived.Value };
        }
于 2013-03-01T09:41:57.087 に答える