如何使用在c#中一个类中声明的变量到另一个类
本文关键字:声明 变量 另一个 一个 何使用 | 更新日期: 2023-09-27 18:11:17
class employee
{
int id;
String name;
int salary;
}
class employeeManager
{
public void ExceptInputOutput()
{
}
}
我已经在雇员类中声明了变量&我想将该变量用于employeeManager
类的ExceptInputOutput()
方法,其中两个类都不是主类。主类将调用employeeManager
类的方法。现在我如何使用变量id
, name
&salary
to ExceptInputOutput()
method
您在employee
中声明的变量有两个使用说明:
c#假定访问修饰符为private
,当没有指定时(对于类成员)-因此您需要显式地将这些变量设置为public
,以便在另一个类中使用它们。
此外,变量不是static
,因此是emplaoyee
实例的一部分——您需要有一个employee
对象来获取值。可以在ExceptInputOutput()
中声明new
,作为参数传递,或者在employeeManager
中声明一个字段。
为什么不在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
}
}
像这样使用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
}
}