c#如何从另一个类中提供构造函数字段

时间:2015-06-07 14:27:01

标签: c# class constructor

我有3个课程:Masina (Car)Destinatie (Destination)MasinaDestinatie (CarDestination)

我需要第三节通过它自己的构造函数来获取车号_nr_masina和目的地_cod_dest的值。

我需要在第三个类中创建一个带有参数的构造函数,用于存储_nr_masina_cod_dest的值。

任何人都知道我该怎么做?我试图将私有字段公之于众,并将其作为参数,但这并不起作用......

课程:

namespace Problema_test
{
    class Masina
    {
        private string _nr_masina = string.Empty;
        private string _valoare = string.Empty;
        private string _an_fabricatie = string.Empty;

        public Masina(string nr_masina,string valoare, string an_fabricatie)
        {
            _nr_masina = nr_masina;
            _valoare = valoare;
            _an_fabricatie = an_fabricatie;
        }

        public string Numar
        {
            get { return _nr_masina; }
            set { _nr_masina = value; }
        }

        public string Valoare
        {
            get { return _valoare; }
            set { _valoare = value; }
        }

        public string Anul
        {
            get { return _an_fabricatie; }
            set { _an_fabricatie = value; }
        }
    }

    class Destinatie
    {
        private string _cod_destinatie = string.Empty;
        private string _adresa = string.Empty;

        public Destinatie(string cod_destinatie, string adresa)
        {
            _cod_destinatie = cod_destinatie;
            _adresa = adresa;
        }

        public string CodDest
        {
            get { return _cod_destinatie; }
            set { _cod_destinatie = value; }
        }

        public string Adresa
        {
            get { return _adresa; }
            set { _adresa = value; }
        }
    }

    class MasinaDestinatie
    {
        // how can i make this work?
        public MasinaDestinatie(string numarMasina, string codDest)
        {

        }
    }
}

1 个答案:

答案 0 :(得分:1)

您可以将值存储在属性

class MasinaDestinatie
{
    public string Numar {get;set;}
    public string CodDest {get;set;}

    public MasinaDestinatie(string numarMasina, string codDest)
    {
        Numar = numarMasina;
        CodDest = codDest;
    }
}

要使用课程,你可以做这样的事情

var masina = new Masina("Dacia","2000","1992");
var destinatie = new Destinatie("123", "Romania");
var masinaDestinatie = new MasinaDestinatie(masina.Numar, destinatie.CodDest);

解决方案2:由于@ blas-soriano sugested你可以存储对象的引用(MasinaDestinatie),这样你就不会有问题(即CodDest仅存在于MasinaDestinatie但不存在于Destinatie,以及其他许多问题。

class MasinaDestinatie
{
    private Masina _masina {get;set;}
    private Destinatie _destinatie {get;set;}

    public string Numar { get { return _masina.Numar; } }
    public string CodDest { get { return _destinatie.CodDest; } }


    public MasinaDestinatie(Masina masina, Destinatie destinatie)
    {
        _masina = masina;
        _destinatie = destinatie;
    }
}

要使用课程,你可以做这样的事情

var masina = new Masina("Dacia","2000","1992");
var destinatie = new Destinatie("123", "Romania");
var masinaDestinatie = new MasinaDestinatie(masina, destinatie);