简体   繁体   English

如何将简单(枚举)参数传递给C#中的类?

[英]How do I pass a simple (enumeration) parameter into a class in C#?

class Person //I'm want to pass the parameter "Gender"
{
    public string firstName;
    public string lastName;
    public int age;
    //public string gender;

This is a piece of code that I'm working with. 这是我正在使用的一段代码。 I'm new to programming, and I'm working with C#. 我是编程的新手,我正在使用C#。 I have an enumeration called "Gender" it consists of "Male" and "Female". 我有一个名为“性别”的枚举,它由“男性”和“女性”组成。 I have a class called "Person" and I want to pass a parameter telling the system that each new "Person" MUST have a gender, male or female. 我有一个名为“Person”的类,我想传递一个参数告诉系统每个新的“人”必须有性别,男性或女性。 I'm pretty sure I'm supposed to pass the parameter near the top close to the class. 我很确定我应该将参数传递给靠近班级的顶部附近。

I want to pass a parameter telling the system that each new Person MUST have a gender 我想传递一个参数,告诉每一个新系统Person必须有一个性别

You enforce that through the constructor: 你通过构造函数强制执行:

public class Person //I'm want to pass the parameter "Gender"
{
    public string firstName;
    public string lastName;
    public int age;
    public Gender gender;  // recommend storing the enum instead of a string

    public Person (Gender gender)
    {
        this.gender = gender;
    }
}

Implementing a constructor with a parameter removes the "default" constructor, so anyone that creates a Person must supply a gender. 使用参数实现构造函数会删除“默认”构造函数,因此创建Person任何Person 必须提供性别。

I's also recommend using properties instead of fields but that's a separate issue... 我还建议使用属性而不是字段,但这是一个单独的问题...

First, you can easily just add a new member for the person's Gender with a type of Gender (which is, I assume, the name of the enum): 首先,您可以轻松地为人类的性别添加一个性别类型的新成员(我认为,这是枚举的名称):

public Gender Gender;

Since you want to force that a person must have a specific gender upon the object's creation you need to stipulate that in the class's constructor : 由于你想强迫一个人在创建对象时必须具有特定的性别,你需要在类的构造函数中规定:

public Person(Gender PersonGender)
{
   Gender = PersonGender;
}

So your class becomes something like this: 所以你的班级会变成这样:

class Person
{
    public string firstName;
    public string lastName;
    public int age;
    public Gender Gender;

    public Person(Gender PersonGender)
    {
       Gender = PersonGender;
    }
}

Note that in C#, unlike in C/C++, it doesn't really matter where you put the methods and the members. 请注意,在C#中,与C / C ++不同, 方法和成员放在何处并不重要。 Just keep them organized for ease of reading. 只是让它们井井有条,便于阅读。

class Person
{
    public string firstName;
    public string lastName;
    public int age;
    public Gender Gender;
}

See MSDN for more information on enum types in C#. 有关C#中enum类型的更多信息,请参阅MSDN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM