首页 文章

一个类数据用于另一个类数据C#

提问于
浏览
2

我有两个已经继承到 XYZ 的类

Country Class

public class country_master : XYZ
{
        private string _id;

        public string id
        {
            get { return _id; }
            set { _id = value; }
        }
        private string _country_code;

        public string country_code
        {
            get { return _country_code; }
            set { _country_code = value; }
        }


        private string _country_name;

        public string country_name
        {
            get { return _country_name; }
            set { _country_name = value; }
        }
}

State Class

public class state_master: XYZ
{
        private string _id;

        public string id
        {
            get { return _id; }
            set { _id = value; }
        }
        private string _state_code;

        public string state_code
        {
            get { return _state_code; }
            set { _state_code= value; }
        }


        private string _state_name;

        public string state_name
        {
            get { return _state_name; }
            set { _state_name= value; }
        }
}
  • 现在,我想在我的 state_master 类中使用 country_name 怎么可能?

谢谢 .

3 回答

  • 2

    您需要 state_master 类中的 country_master 类型的变量 . 然后,您可以访问属性 country_name .

    不幸的是,交叉继承是不可能的 . (如果你有一个兄弟,你不能只用他的手,虽然你从同一个父母那里继承 . 你需要你的兄弟亲自 . )

    例:

    public class state_master: XYZ
    {
        private country_master _cm;
    
        public country_master cm
        {
            get { return _cm; }
            set { _cm = value; }
        }
    
        public void state_method()
        {
            this.cm = new country_master();
            this.cm.country_name;
        }
    
    }
    

    另一种可能性当然是在调用方法时从外部传递变量

    public void state_method(string country_name)
    {
        // use country name
    }
    

    呼叫站点:

    state_master sm = new state_master();
    country_master csm = new country_master();
    
    sm.state_method(cm.countr_name);
    

    (现在你要求你的兄弟伸出援助之手)

  • 3

    皮肤猫的方法不止一种 .

    您可以创建country_master的新实例:

    public class state_master: XYZ
    {
        private country_master CountryMaster;
        // Class constructor
        public state_master()
        {
            CountryMaster = new country_master();
        }
    
        private string _id;
        ...
    

    或者将country_master的现有实例传递给构造函数:

    public class state_master: XYZ
    {
        private country_master CountryMaster;
        // Class constructor
        public state_master(country_master cm)
        {
            CountryMaster = cm;
        }
    
        private string _id;
        ...
    

    并称之为

    country_master MyCountry = new country_master();
    state_master MyState = new state_master(MyCountry);
    
  • 0

    您可以更改代码,以便state_master继承country_master

    public class state_master: country_master
    

相关问题