1

ちょっと基本的な質問だと思いますが、あるオブジェクトがタイプ A または B の別のオブジェクトを所有するようにしたい場合、そのオブジェクトを使用するアプリケーションはどのようにして特定の属性にアクセスできるのでしょうか? 例えば

public abstract class Animal
{
     private int Age;
     // Get Set
}

public class Tiger: Animal
{
     private int NoStripes;
     // Get Set
}

public class Lion : Animal
{
     private bool HasMane;
     // Get Set
}

public class Zoo
{
     private Animal animal;
     // Get Set
}

public static void Main()
{
     Zoo zoo = new Zoo();
     zoo.animal = new Tiger();

     // want to set Tiger.NoStripes
}
4

3 に答える 3

2

にキャストする必要がありzoo.AnimalますTiger

または、次のようなものを試すことができます

public abstract class Animal
{
    public int Age;
    // Get Set
}

public class Tiger : Animal
{
    public int NoStripes;
    // Get Set
}

public class Lion : Animal
{
    public bool HasMane;
    // Get Set
}

public class Zoo<T> where T : Animal
{
    public T animal;
    // Get Set
}

Zoo<Tiger> zoo = new Zoo<Tiger>();
zoo.animal = new Tiger();
zoo.animal.NoStripes = 1;
于 2010-12-22T12:03:24.857 に答える
0

直接の答えは、することです

public static void Main() {
    Zoo zoo = new Zoo();
    zoo.animal = new Tiger();

    ((Tiger)zoo.Animal).NoStripes = 10;
}

もちろん、これが機能するためには、それzoo.Animalが実際にはTiger. を使用zoo.Animal is Tigerしてそれをテストできます(ただし、as演​​算子は vs. よりも好ましいisです)。

ただし、一般に、このようなプログラムの設計はあまりいいにおいがしません。記述しなければならないコードはおそらく面倒です。

于 2010-12-22T12:03:50.823 に答える
0

これが継承とポリモーフィズムの要点です。

Animal のインスタンスが実際には Tiger のインスタンスであると判断できる場合は、次のようにキャストできます。

((Tiger)zoo.Animal).NoStripes = 1;

ただし、Tiger ではない Animal のインスタンスでこれを実行しようとすると、実行時例外が発生します。

例えば:

Zoo zoo = new Zoo();
zoo.animal = new Tiger();
((Tiger)zoo.Animal).NoStripes = 1; //Works Fine

((Lion)zoo.Animal).NoStripes = 1; //!Boom - The compiler allows this, but at runtime it will fail.

キャストが失敗した場合に例外の代わりに、null を返す「as」キーワードを使用する別のキャスト構文があります。これは素晴らしいことのように思えますが、実際には、後で null オブジェクトが消費されたときに微妙なバグが発生する可能性があります。

Tiger temp = zoo.Animal as Tiger; //This will not throw an exception
temp.NoStripes = 1; //This however, could throw a null reference exception - harder to debug
zoo.Animal = temp;

null参照例外を回避するには、もちろんnullチェックを行うことができます

Tiger temp = zoo.Animal as Tiger; //This will not throw an exception
if (temp != null)
{
    temp.NoStripes = 1; //This however, could throw a null reference exception - harder to debug
    zoo.Animal = temp;
}
于 2010-12-22T12:04:13.507 に答える