在初始化一个类的实例时如何传递另一个类的实例?

时间:2019-11-29 20:41:31

标签: c# class

    public class A
    {
        public C instanceOfCInA;
        public double a;
        public double b;
    }
    public class B
    {
        public C instanceOfCInB;
        public A instanceOfAInB;
    }

    public class C
    {
        //not important
    }

如何将instanceOfCInB传递到instanceOfAInB的instanceOfCInA中?

1 个答案:

答案 0 :(得分:0)

使用构造函数(ctor)并将另一个类的实例用作参数。 A中C的示例:

namespace ConsoleApp2
{
    public class Program
    {

        static void Main(string[] args)
        {
            C c = new C();
            A a = new A(c);
            B b = new B(c, a);
        }
    }


    public class A
    {
        public A(C c)
        {
            instanceOfCInA = c;
        }

        public C      instanceOfCInA;
        public double a;
        public double b;
    }

    public class B
    {
        public B(C c, A a)
        {
           instanceOfCInB = c;
           instanceOfAInB = a;
        }

        public C instanceOfCInB;
        public A instanceOfAInB;
    }

    public class C
    {
        //not important
    }
}