【问题标题】:is it possible that can create an object from class person inside a class employee and access to the methods in C#.net是否可以从班级员工内部的班级人员创建一个对象并访问 C#.net 中的方法
【发布时间】:2015-05-01 02:13:47
【问题描述】:

我可以从员工类中的人员类创建一个对象,并使用我在员工类中创建的人员对象通过员工类访问类人员的方法和成员吗

public class Person
{
    protected string _name;
    public int _age;

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }
}

class Employee
{
    Person person = new Person();
}

【问题讨论】:

  • 是的,你可以。问之前有没有试过?
  • 为什么不只是public class Employee { public Person PersionalInfo {get; set;} /* other Employee properties*/ }

标签: c# class oop object


【解决方案1】:

你是这个意思吗?

public class Employee
{
    private Person person = new Person();

    public string Name
    {
        get { return person.Name; }
        set { person.Name = value; }
    }

    public int Age
    {
        get { return person.Age; }
        set { person.Age = value; }
    }
}

【讨论】:

    【解决方案2】:

    你可以这样做:

    class Employee
    {
        Person person = new Person();
    
        public string Name 
        {
            get { return person.Name; }
            set { person.Name = value } 
        }
    
        public int Age
        {
            get { return person.Age; }
            set { person.Age = value; }
        }
    }
    

    您可以考虑提供一个“人”接口并让员工类实现它。

    【讨论】:

    • 谢谢。我忘了把对象放在方法里面。因为我把它放在了方法之外。
    【解决方案3】:

    是的,因为类 Person 是公共的。

    【讨论】:

      猜你喜欢
      • 2011-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-28
      • 2019-10-11
      • 2020-09-11
      • 1970-01-01
      • 2016-10-26
      相关资源
      最近更新 更多