类(x)的对象作为类(y)的属性

时间:2019-03-18 01:23:44

标签: c# oop object constructor attributes

我无法找到答案,因为我不知道如何放置。

我有一个Car()类和Owner()类。我需要的是拥有一个“拥有者”对象,作为Car()类的简单属性,因此,一旦实例化Car()对象,我就可以将其作为参数传递。

我的Owner()类:

class Owner
{
    public Owner(string address){
        this.address = address;
    }
}

我的Car()类:

class Car
{
    public Car(object owner){ // what type to use?
        this.owner = owner; 
    }

    private object owner; // what type to use?
}

还有我的Main()类:

static void Main(string[] args){
    Owner owner1 = new Owner("street foo city bar");
    Car car1 = new Car(owner1); // this needs to work
}

很明显,对属性使用'object'类型没有做到这一点。一旦我打印,我得到'myProjectName.Owner'。预先谢谢你。

2 个答案:

答案 0 :(得分:1)

public class Car
{
    public Car(Owner owner)
    {
        this.Owner = owner;
    }

    //Since Owner is public, you don't have to create a getter method for this. i.e GetOwner()
    public Owner Owner;
}

public class Owner
{
    //Since address is private, you'll have to create a public getter for this
    private string address;

    public Owner(string address)
    {
        this.address = address;
    }

    //public getter for the address
    public string GetAddress()
    {
        return this.address;
    }
}

public class Main
{
    static void main(string[] args)
    {
        Owner owner1 = new Owner("street address");
        Car car1 = new Car(owner1);

        car1.Owner.GetAddress();
    }
}

答案 1 :(得分:1)

您可以按以下方式编写代码,编写公共方法以返回所需的对象。

 class Program
    {
        static void Main(string[] args)
        {
            Owner owner1 = new Owner("street foo city bar");
            Car car1 = new Car(owner1); // this needs to work

            Console.WriteLine("Car 1 owner address : " + car1.getOwner().getAddress());
            Console.ReadKey();


        }
    }


    class Car
    {
        private Owner owner;  // same here\
        public Car(Owner owner)
        { // use Owner class
            this.owner = owner;
        }

        public Owner getOwner() // write a public method to return owner
        {
            return this.owner;
        }


    }


    class Owner
    {

        private string address; // this 
        public Owner(string address)
        {

            this.address = address;
        }

        public string getAddress() // write a public method to return address
        {
            return this.address;
        }
    }
相关问题