C# property get,set 不同类型

发布于 2024-11-01 05:46:11 字数 1459 浏览 7 评论 0原文

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

        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”

我应该如何编写属性的设置访问器?

更新:

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

I have such an enum and a property.

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

This is my class:

public class Employee
{
     private Type employeeType;
}

And I want to create such a constructor:

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

EDIT:

Cannot implicitly convert type 'Payroll.Employee.Type' to 'string'

How should I write the set accessor of the property?

UPDATE:

I wanted the get accessor to return string and set accessor to take parameter type Employee.Type. I learned that it is impossible to do this in a property according to the C# spec. I have to write separate getter and setter methods.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

拥醉 2024-11-08 05:46:11

请改用 DescriptionAttribute

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

那么你就拥有了

public Type EmployeeType {get; set;}

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

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

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

Use DescriptionAttribute instead.

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

Then you would just have an

public Type EmployeeType {get; set;}

property. And if somebody wanted to write it out, they could get the description. I'd also call it Type instead of EmployeeType, because the call myEmployee.EmployeeType sounds redundant. Your other option might be to unroll the property and have two methods

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

Not quite as elegant as a property, but quickly does the job. Also remember that properties in IL are just methods.

一直在等你来 2024-11-08 05:46:11

像这样:

EmployeeType = (Type)Enum.Parse(typeof(Type), value);

Like this:

EmployeeType = (Type)Enum.Parse(typeof(Type), value);
贱贱哒 2024-11-08 05:46:11

我建议你不要使用单词类型,你需要解析枚举:

set
{
    employeeType = (Type)Enum.Parse(typeof(Type), value);
}

编辑:

首先,我必须重申不要使用 Type 一词来表示枚举或返回属性的字符串。其次,在这里使用枚举和 switch 可能会给你带来麻烦,但默认值可能会帮你摆脱困境。

public enum WorkType
{
    Hourly = 1,
    Salary = 2,
    None = 3
};

// Initialize this to prevent craziness
private WorkType employeeType = WorkType.None;
public string EmployeeType
{
    get
    {
        // I'm not sure why you want to return a string
        // in this property but whatevs.
        // First make sure that you have a valid enum
        if ((int)employeeType > 3 || (int)employeeType < 1)
            employeeType = WorkType.None;
        return employeeType.ToString();   // Don't need a switch, just call ToString()
        }

        set
        {
            // This might be better served with a TryParse. This will
            // be more fault tolerant if someone using your class passes
            // in an invalid WorkType.
            if(!TryParse(typeof(WorkType), value, out employeeType))
                employeeType = WorkType.None;
        }
    }
}

我怀疑您在转换中遇到的问题是您使用的分配不是字符串,例如:

WorkType someType = WorkType.None;
this.EmployeeType = someType;   // Exception is here

这是无效的情况,因为 someType 是类型,而 EmployeeType (value) 是字符串。要解决这个问题,您需要将其分配为:

this.EmployeeType = someType.ToString();

所有这些都归结为非常愚蠢,因为它可以通过以下简单的事情来完成:

public enum WorkType
{
    Hourly = 1,
    Salary = 2,
    None = 3
};

public WorkType EmployeeType { get; set; }
// Any time you want to access the value of EmployeeType as a string you would
// simply use the following line:
// EmployeeType.ToString();

I recommend you don't use the word type, and you need to parse the enum:

set
{
    employeeType = (Type)Enum.Parse(typeof(Type), value);
}

Edit:

First, I can't reiterate enough not to use the word Type for either the enum OR the string for returning the property. Second, the usage of enums here with switch could land you in trouble, but the default may bail you out.

public enum WorkType
{
    Hourly = 1,
    Salary = 2,
    None = 3
};

// Initialize this to prevent craziness
private WorkType employeeType = WorkType.None;
public string EmployeeType
{
    get
    {
        // I'm not sure why you want to return a string
        // in this property but whatevs.
        // First make sure that you have a valid enum
        if ((int)employeeType > 3 || (int)employeeType < 1)
            employeeType = WorkType.None;
        return employeeType.ToString();   // Don't need a switch, just call ToString()
        }

        set
        {
            // This might be better served with a TryParse. This will
            // be more fault tolerant if someone using your class passes
            // in an invalid WorkType.
            if(!TryParse(typeof(WorkType), value, out employeeType))
                employeeType = WorkType.None;
        }
    }
}

I suspect the problem you're running into with the conversion is that you're using an assignment that is not a string like:

WorkType someType = WorkType.None;
this.EmployeeType = someType;   // Exception is here

This is an invalid case because someType is a type and EmployeeType (value) is a string. To fix this you need to assign it with:

this.EmployeeType = someType.ToString();

All of this sort of boils down to pretty silly because it can be accomplished with something as simple as:

public enum WorkType
{
    Hourly = 1,
    Salary = 2,
    None = 3
};

public WorkType EmployeeType { get; set; }
// Any time you want to access the value of EmployeeType as a string you would
// simply use the following line:
// EmployeeType.ToString();
笔芯 2024-11-08 05:46:11

理想情况下,您仍然应该有一个可以设置/获取属性可以附加到的私有成员。从那里,您可以使用另一种方法来获取“人类可读/格式化”版本。例如

public enum EmployeeType
{
  Hourly = 1,
  Salary = 2,
  None = 3
}

private EmployeeType _EmployeeType;

public EmployeeType EmployeeType
{
  get { return this._EmployeeType; }
  set { this._EmployeeType = value; }
}

,然后你有一个方法来返回格式化版本

public String EmployeeType()
{
  switch (this._EmployeeType)
  {
    case EmployeeType.Hourly:
      return "Hourly Employee";
    case EmployeeType.Salary:
      return "Salary Employee";
    default:
      return "None";
  }
}

,或者这就是我要做的。否则,枚举没有意义,您应该只使用字符串并验证输入/输出是否在预先选择的有效值范围内。

编辑 我推荐这样做只是因为字符串输入并尝试将其与枚举的名称对齐(正如其他人所建议的那样)对我来说似乎有缺陷。特别是随着“小时工”向“小时工”的转变。 (obj).EmployeeType = "Hourly Employee" 无法与 Enum.Parse 一起使用,因为没有与输入匹配的有效枚举。

EDITv2我实际上喜欢@Yuriy的< /a> 更好地使用DescriptionAttribute。保持其类型结构,但打印时使其清晰易读。

Ideally you should still have a private member you can set/get that the property can attach to. From there, you can make another method to get the "Human Readable/Formatted" version. e.g.

public enum EmployeeType
{
  Hourly = 1,
  Salary = 2,
  None = 3
}

private EmployeeType _EmployeeType;

public EmployeeType EmployeeType
{
  get { return this._EmployeeType; }
  set { this._EmployeeType = value; }
}

Then you have a method to return the formatted version

public String EmployeeType()
{
  switch (this._EmployeeType)
  {
    case EmployeeType.Hourly:
      return "Hourly Employee";
    case EmployeeType.Salary:
      return "Salary Employee";
    default:
      return "None";
  }
}

or that's how I would do it. Otherwise, an enum doesn't make sense and you should just work with a string and validate the input/output to fall within pre-selected valid values.

EDIT I recommend this just because a string input and trying to align it with the name of an enum (as others have suggested) just appears flawed to me. Especially with the transition of "Hourly" to "Hourly Employee". (obj).EmployeeType = "Hourly Employee" won't work with using Enum.Parse because there is no valid enum matching the input.

EDITv2 I actually like @Yuriy's use of the DescriptionAttribute better. Keep it type-structured, but make it legible when printed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文