【问题标题】:One class data use in another class data C#一个类数据在另一类数据中使用 C#
【发布时间】:2016-12-16 16:52:41
【问题描述】:

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

国家类

公共课 country_master : XYZ { 私有字符串_id; 公共字符串标识 { 得到{返回_id; } 设置 { _id = 值; } } 私人字符串_country_code; 公共字符串 country_code { 得到 { 返回 _country_code; } 设置 { _country_code = 值; } } 私人字符串 _country_name; 公共字符串国家名称 { 得到 { 返回 _country_name; } 设置 { _country_name = 值; } } }

状态类

公共类 state_master: XYZ { 私有字符串_id; 公共字符串标识 { 得到{返回_id; } 设置 { _id = 值; } } 私有字符串_state_code; 公共字符串 state_code { 得到 { 返回 _state_code; } 设置 { _state_code= 值; } } 私有字符串_state_name; 公共字符串 state_name { 得到 { 返回 _state_name; } 设置 { _state_name= 值; } } }
  • 现在,我想在我的state_master 类中使用country_name,这怎么可能?

谢谢。

【问题讨论】:

  • 你想怎么用?在一个方法? state_master 的每个实例都有一个唯一实例?
  • 在 state_master 方法中。
  • 兄弟,state_master 类只能使用XYE 属性,如果你想使用country_name,你可以在state_master 类中使用country_master 作为属性,或者也许将country_name 移动到XYZ 类。
  • XYZ 被使用,因为使用了另一个属性。
  • 任何其他类似界面的方式???

标签: c#


【解决方案1】:

您的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);

(现在你要请你的兄弟帮忙)

【讨论】:

    【解决方案2】:

    给猫剥皮的方法不止一种。

    您可以创建一个 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);
    

    【讨论】:

      【解决方案3】:

      你可以改变你的代码,让 state_master 继承 country_master

      public class state_master: country_master 
      

      【讨论】:

      • public class state_master : XYZ 是强制写入的,因为 XYZ 属性及其在 state_master 类中使用的方法。
      • 由于 country_master 继承了 XYZ,那么 state_master 将同时继承 XYZ 和 country_master
      • @Ehsan.Saradar 你试过了吗?从 2 个基类继承?
      • 是的,state_master 继承 country_master 而 country_master 继承 XYZ
      猜你喜欢
      • 1970-01-01
      • 2022-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多