Tim*_*çin 5 c# get properties accessor set
我有这样的枚举和财产.
public enum Type
{
Hourly = 1,
Salary = 2,
None = 3
};
public string EmployeeType
{
get
{
string type;
switch (employeeType)
{
case Type.Hourly:
type = "Hourly Employee";
break;
case Type.Salary:
type = "Salary Employee";
break;
default:
type = "None";
break;
}
return type;
}
// **EDIT:**
// Now I am trying to parse the string as enum Type.
// But Constructor still waits a string to set EmployeeType.
set
{
employeeType = (Type)Enum.Parse(typeof(Type), value);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的班级:
public class Employee
{
private Type employeeType;
}
Run Code Online (Sandbox Code Playgroud)
我想创建这样一个构造函数:
Employee(Employee.Type type)
{
EmployeeType = type;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
无法将类型'Payroll.Employee.Type'隐式转换为'string'
我该如何编写属性的set访问器?
更新:
我希望get访问器返回字符串并设置访问器以获取参数类型Employee.Type.我了解到根据C#规范,不可能在属性中执行此操作.我必须编写单独的getter和setter方法.
Yur*_*ich 12
public enum Type
{
[Description("Hourly Employee")]
Hourly = 1,
[Description("Salary Employee")]
Salary = 2,
[Description("None")]
None = 3
};
Run Code Online (Sandbox Code Playgroud)
然后你会有一个
public Type EmployeeType {get; set;}
Run Code Online (Sandbox Code Playgroud)
属性.如果有人想写出来,他们可以得到描述.我也称之为,Type而不是EmployeeType,因为电话myEmployee.EmployeeType听起来多余.您的另一个选择可能是展开该属性并有两种方法
public string GetEmployeeType() { //your switch statement }
public void SetEmployeeType(EmployeeType type)
{
_type = type;
}
Run Code Online (Sandbox Code Playgroud)
不像房产那么优雅,但很快就完成了工作.还记得IL中的属性只是方法.