C#中一个类的数据在另一个类中的使用

3
我有以下两个类,它们已经继承到XYZ中。 国家类
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; } } }
州类
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= value; } set { _state_name= value; } } }
  • 现在,我想在我的state_master类中使用country_name,这可能吗?
谢谢。

2
你想如何使用它?在一个方法中?每个state_master实例都有一个唯一的实例? - doctorlove
在 state_master 方法中。 - Ketul Soni
兄弟,state_master 类只能使用 XYE 属性,如果你想使用 country_name,可以在 state_master 类中作为属性拥有一个 country_master 的实例,或者将 country_name 移动到 XYZ 类中。 - Badro Niaimi
由于使用了另一个属性,所以需要使用XYZ。 - Ketul Soni
任何其他方式,例如接口? - Ketul Soni
一个接口只是双方必须遵守的合同。你仍需要在两个类中实现属性,每个对象都将有自己的值。 - Mong Zhu
3个回答

3

你需要在你的 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);

0

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

public class state_master: country_master 

由于state_master类中使用了XYZ属性和方法,因此编写public class state_master:XYZ是必需的。 - Ketul Soni
由于 country_master 继承了 XYZ,因此 state_master 将同时继承 XYZ 和 country_master。 - Ehsan.Saradar
@Ehsan.Saradar 你试过这个吗?继承两个基类的方法? - Mong Zhu
是的,state_master 继承自 country_master,而 country_master 则继承自 XYZ。 - Ehsan.Saradar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接