c#属性获取,设置不同类型

标签 c# get properties set accessor

我有这样一个枚举和一个属性。

        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);
            }
        }

这是我的课:

public class Employee
{
     private Type employeeType;
}

我想创建这样一个构造函数:

Employee(Employee.Type type) 
{
      EmployeeType = type;
}

编辑:

无法将类型“Payroll.Employee.Type”隐式转换为“string”

属性的set访问器应该怎么写?

更新:

我希望 get 访问器返回字符串并设置访问器采用参数类型 Employee.Type。我了解到,根据 C# 规范,不可能在属性中执行此操作。我必须编写单独的 getter 和 setter 方法。

最佳答案

使用DescriptionAttribute反而。

public enum Type
{
    [Description("Hourly Employee")]
    Hourly = 1,
    [Description("Salary Employee")]
    Salary = 2,
    [Description("None")]
    None = 3
};

那么你就会有一个

public Type EmployeeType {get; set;}

属性(property)。如果有人想把它写出来,他们可以获得描述。我还将其称为 Type 而不是 EmployeeType,因为调用 myEmployee.EmployeeType 听起来多余。您的另一个选择可能是展开属性并有两种方法

public string GetEmployeeType() { //your switch statement }
public void SetEmployeeType(EmployeeType type)
{
    _type = type;
}

不像属性那么优雅,但很快就完成了工作。还要记住,IL 中的属性只是方法。

关于c#属性获取,设置不同类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5679385/

相关文章:

c# - 如何轻松支持重复的异步/同步方法?

c# - 将二进制字符串表示形式转换为字节数组

iphone - _property 和 self.property 的区别

c# - 发送 Gmail 电子邮件

c# - asp.net 核心路由值到基本 Controller 并可选择覆盖操作

get - access-control-allow-origin is not allowed 错误,但如果省略则预期从获取请求 Flutter web

javascript - 如何在 $.get URL 中调用 this.id

python - 连接python服务器和html

jquery - 如何覆盖CSS属性?

PHP:将类变量声明为 stdClass 对象