Base 클래스의 C #의 C #의 일반 목록에서 파생 및 기본 클래스를 믹스 할 수 있습니까?

StackOverflow https://stackoverflow.com//questions/11665887

문제

유형 기본 클래스의 C #의 일반 목록에서 파생 및 기본 클래스를 믹스 할 수 있습니까?나는 왜 그렇게하지 않는 이유를 보지 못한다. 나는 이것에 대한 명확한 답변을 보지 못한다. 그러나 오늘베이스 클래스의 일반적인 목록으로 오늘들을 놀아 라.문제.그러나 유도 / 기본 수업에서 항상 고유 한 일반적인 UPCAST / DownCast 제한 사항을 제외하고 잠재적 인 문제가있을 수 있는지 궁금합니다.내가 묻는 이유는 다음과 같습니다. C #의 일반 목록이 C ++의 ArrayList라고하는 것과 동일하게 작동하는지 모르겠습니다. 즉, 이와 같은 '유형'을 혼합하기 위해 컴파일하는 동안 불만 사항을 얻을 수 있는지 여부입니다 (베이스 vs 파생 클래스).나는 불만없이 오늘날 수많은 예를 들어 왔지만 문제가 있는지 여부를 확인하고 싶습니다.

도움이 되었습니까?

해결책

C # 클래스 유형은 참조 유형입니다.C ++ 클래스 유형은 .NET World의 값 유형이라고합니다.적절한 비교는 기본 클래스 포인터의 C ++ 목록이며, 이는 문제없이 파생 클래스에 포인터를 저장할 수 있습니다.

그래서 그렇습니다. 괜찮습니다.

다른 팁

 using System;
 using System.Collections.Generic;

 namespace DoFactory.GangOfFour.Composite.Structural
{
/// <summary>
/// MainApp startup class for Structural 
/// Composite Design Pattern.  
/// </summary>
class MainApp
{
    /// <summary>
    /// Entry point into console application.
    /// </summary>
    static void Main()
    {
        // Create a tree structure
        Composite root = new Composite("root");
        root.Add(new Leaf("Leaf A")); //1st Add for root
        root.Add(new Leaf("Leaf B")); //2nd Add for root
        Console.WriteLine(" ....");
        root.Display(1);
        Console.WriteLine("...........");
        Composite comp = new Composite("Composite X");
        comp.Add(new Leaf("Leaf XA"));
        root.Add(comp); //add comp to root //3rd Add for root

        DerivedComposite myDerivedComposite = new DerivedComposite("derived member",      1000);
        Console.WriteLine("Show the special int, string for DerivedComposite");
        myDerivedComposite.mySpecialVariablesAre();
        Console.WriteLine("........");

        root.Add(myDerivedComposite); //4th Add for root

        Composite SecondRoot = new Composite("SecondRoot");
        SecondRoot.Add(new Leaf("Leaf fA"));


        SecondRoot.Add(myDerivedComposite); //add to SecondRoot

        root.Add(SecondRoot); //add comp to root ; //5th Add for root
        //// Recursively display tree again, after adding
        root.Display(1);

        Console.WriteLine("Now get List read back");
        Console.WriteLine("show List elements for root (should be five)");
        root.DisplayList();

        Console.WriteLine("Show List elements for comp (should be one)");
        comp.DisplayList();
        Console.WriteLine("Show List ele for SecondRoot (should be 2)");
         SecondRoot.DisplayList();

        // Wait for user
        Console.ReadKey();
    }
}


/// <summary>
/// The 'Component' abstract class
/// </summary>
abstract class Component
{
    protected string name;

    // Constructor
    public Component(string name)
    {
        this.name = name;
    }

    public abstract void Add(Component c);
    public abstract void Remove(Component c);
    public abstract void Display(int depth);
    public abstract void printSpecialInt();
}

/// <summary>
/// The 'Composite' class
/// </summary>
class Composite : Component
{
    private List<Component> _children = new List<Component>(); 
    //This Generic List was potentially troublesome but it executed fine
    protected int specialbaseInt;
    // Constructor
    public Composite(string name)
        : base(name)
    {
        specialbaseInt = -1;
    }

    public override void Add(Component component)
    {
        _children.Add(component);
    }

    public override void Remove(Component component)
    {
        _children.Remove(component);
    }

    public override void Display(int depth)
    {
        Console.WriteLine(new String('-', depth) + name);

        // Recursively display child nodes
        foreach (Component component in _children)
        {
            component.Display(depth + 2); //calls .Display again, is recursive
        }
    }

    public void DisplayList()
    {
        int ijk = _children.Count;
        Console.WriteLine("# elements in this List: {0}", ijk);
        foreach (Component c in _children)
        {
            int ii = c.GetHashCode();
            Type type = c.GetType();
            Console.WriteLine("GetHashCode, Type on list: {0}, {1}", ii, type.FullName);

            c.printSpecialInt();

        }
    }

    public override void printSpecialInt()
    {
        Console.WriteLine("special int (at base class): {0}", specialbaseInt);
    }
}

class DerivedComposite : Composite
{
    public string myExtraString;
    public int mySpecialInt;

    public DerivedComposite(string name,int ianint)
        : base(name)
    {
        myExtraString = name;
        mySpecialInt = ianint + 10;
        specialbaseInt = ianint;
    }

    public void mySpecialVariablesAre()
    {
        Console.WriteLine("The string, int, specialbaseInt are!- {0}, {1}, {2}", myExtraString, mySpecialInt, specialbaseInt);
    }

    public override void printSpecialInt()
    {
        Console.WriteLine("The string, int, specialbaseInt are (at derived): {0}, {1},    {2}", myExtraString, mySpecialInt, specialbaseInt);
    }

}

/// <summary>
/// The 'Leaf' class
/// </summary>
class Leaf : Component
{
    // Constructor
    public Leaf(string name)
        : base(name)
    {
    }

    public override void Add(Component c)
    {
        Console.WriteLine("Cannot add to a leaf");
    }

    public override void Remove(Component c)
    {
        Console.WriteLine("Cannot remove from a leaf");
    }

    public override void Display(int depth)
    {
        Console.WriteLine(new String('-', depth) + name);
    }

    public override void printSpecialInt()
    {
        Console.WriteLine("at Leaf printSpecialInt");
    }
}

/// <summary>
/// The 'Leafail' class //try and make it fail
/// </summary>
class Leafail : Component
{
    // Constructor
    public Leafail(string name)
        : base(name)
    {
        myExtraString = "Hi, I am Leafail";
        mySpecialInt = 123;
    }

    public string myExtraString;
    public int mySpecialInt;

    public override void Add(Component c)
    {
        Console.WriteLine("Cannot add to a leafail");
    }

    public override void Remove(Component c)
    {
        Console.WriteLine("Cannot remove from a leafail");
    }

    public override void Display(int depth)
    {
        Console.WriteLine(new String('-', depth) + name);
    }

    public void mySpecialVariablesAre()
    {
        Console.WriteLine("The string, int are: {0}, {1}", myExtraString,mySpecialInt);
    }
    public override void printSpecialInt()
     {
         Console.WriteLine("at Leafail printSpecialInt");
     }
}


}
.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top