我知道这是一个绝对的保姆,但不知何故,我并没有得到它的支持。可以说,我有一个类Person
,如下所示 -
public class Person
{
//Constructor...
public Person( string name, Gender gender)
{
this.Name = name;
this.Gender = gender;
}
//Member variables...
private string _Name;
public string Name
{
get
{
return _Name;
}
set
{
_Name = value;
}
}
private Gender _Gender;
public Gender Gender
{
get
{
return _Gender;
}
set
{
_Gender = value;
}
}
}
public enum Gender
{
Male = 0,
Female = 1
}
我不希望Gender
再次成为enum
,我希望将其替换为struct
并以与上述相同的方式将其作为参数传递到constructor
班级的Person
时,我create a new object of person class I am able to assign the gender
以及那个人。我怎么做?
谢谢。
答案 0 :(得分:2)
您可以通过enum
以这种方式模仿 struct
:
// Gender according ISO/IEC 5218
// See: http://en.wikipedia.org/wiki/ISO/IEC_5218
public struct Gender {
private int m_Value;
private Gender(int value) {
m_Value = value;
}
private Gender() {
m_Value = 0;
}
public int IsoValue {
get {
return m_Value;
}
}
public override int GetHashCode() {
return m_Value;
}
public override bool Equals(object obj) {
if (!(obj is Gender))
return false;
return ((Gender) obj).m_Value == m_Value;
}
public static Boolean operator ==(Gender left, Gender right) {
return left.m_Value == right.m_Value;
}
public static Boolean operator !=(Gender left, Gender right) {
return left.m_Value != right.m_Value;
}
public static readonly Gender Male = new Gender(1);
public static readonly Gender Female = new Gender(2);
// E.g. "XYZ Corporation"
public static readonly Gender NotApplicable = new Gender(5);
// E.g. "Brown" - Mr or Mrs?
public static readonly Gender Unknown = new Gender(0);
}
...
class Person {
public string Name { get; private set; }
public Gender Gender { get; set; }
public Person(string name, Gender gender) {
Name = name;
Gender = gender;
}
}
答案 1 :(得分:1)
我仍然不明白为什么你必须这样做,但如果你应该这样做,你可以这样做:
class Person
{
public string Name { get; private set; }
public Gender Gender { get; private set; }
public Person(string name, Gender gender)
{
Name = name;
Gender = gender;
}
}
struct Gender
{
private int _type;
public bool IsMale
{
get { return _type == 0; }
set { _type = value ? 0 : 1; }
}
public bool IsFemale
{
get { return _type == 1; }
set { _type = value ? 1 : 0; }
}
}
使用它:
var p1 = new Person("John", new Gender {IsMale = true});
var p2 = new Person("Jane", new Gender {IsFemale = true});