如何将一个类中声明的变量用于C#中的另一个类

时间:2015-09-04 16:19:04

标签: c#

class employee
{
    int id;
    String name;
    int salary;
}

class employeeManager
{
   public void ExceptInputOutput()
    { 
    }
}

我已在员工类中声明了变量&想要将该变量用于ExceptInputOutput()类的方法employeeManager,其中两个类都不是主类。主类将调用employeeManager类的方法。现在我该如何使用变量idname& salaryExceptInputOutput()方法。

3 个答案:

答案 0 :(得分:1)

为什么不将员工注入employeeManager类?

public class employee
{
    public int id { get; set; }
    public String name { get; set; }
    public int salary { get; set; }
}

class employeeManager
{
   public void ExceptInputOutput(employee model)
   { 
       // model.id
   }
}

答案 1 :(得分:1)

您在employee中声明的变量有两个使用说明:

当没有指定(对于类成员)时,C#假定访问修饰符为private - 因此,您需要明确地使这些变量public从另一个类中使用它们。

此外,varuables不是static,因此是emplaoyee实例的一部分 - 您需要有一个employee对象来获取值。这可以在new中声明ExceptInputOutput(),作为参数传递,或在employeeManager中声明一个字段。

答案 2 :(得分:0)

使用inheritance像这样:

public class employee
{
    public int ID {get;set;}
    public String Name {get;set;}
    public int Salary {get;set;}
}

public class employeeManager : employee
{
   public void ExceptInputOutput()
   { 
       //ID,Name,Salary are accessible
   }
}