CSharp中的枚举与常量

前言

枚举(Enum)是一种常用的数据类型,用于定义一组命名的常量值。使用枚举可以增加代码的可读性和可维护性。

在XAML中使用枚举时,可以通过引用枚举类型和指定枚举值来设置控件的属性。

枚举定义

定义枚举类型

1
2
3
4
5
6
public enum Gender
{
Male,
Female,
Other
}

或者

1
2
3
4
5
public enum WsType
{
QuestionsStart = 201,
ShareBegin = 601
}

或者

1
2
3
4
5
6
7
8
9
10
public enum Days
{
Monday = "Monday",
Tuesday = "Tuesday",
Wednesday = "Wednesday",
Thursday = "Thursday",
Friday = "Friday",
Saturday = "Saturday",
Sunday = "Sunday"
}

int枚举

1
2
3
4
5
public enum WsType
{
QuestionsStart = 201,
ShareBegin = 601
}

即使是int类型的,我们也不能直接取值

我们得这样取值

1
2
int value = (int)WsType.QuestionsStart;
Console.WriteLine(value); // 输出 201

字符串枚举

在C#中,枚举(Enum)值通常由整数类型(如 int)表示。

这意味着枚举成员默认情况下是整数,而不是字符串。

然而,你可以为枚举成员指定字符串字面量,但底层仍然是整数。

以下是使用字符串字面量的枚举示例:

1
2
3
4
5
6
7
8
9
10
public enum Days
{
Monday = "Monday",
Tuesday = "Tuesday",
Wednesday = "Wednesday",
Thursday = "Thursday",
Friday = "Friday",
Saturday = "Saturday",
Sunday = "Sunday"
}

在上面的例子中,每个枚举成员都关联了一个字符串字面量。

但是,当你在代码中使用这些枚举成员时,它们仍然会被编译为整数。

例如,Days.Monday 在底层实际上是一个整数值,而不是字符串 Monday

如果你需要在代码中将枚举成员与字符串进行比较或操作,你可以使用 ToString() 方法来获取枚举成员的字符串表示。例如:

1
2
Days day = Days.Monday;
string dayName = day.ToString(); // dayName 将是 "Monday"

在XAML中,你可以使用 x:Static 来获取枚举成员的字符串表示:

1
2
3
<StackPanel>
<TextBlock Text="{x:Static local:Days.Monday}" />
</StackPanel>

在这种情况下,TextBlockText 属性将显示字符串 Monday

总结一下,虽然在代码层面你可以为枚举成员指定字符串字面量,但它们在后台仍然是整数。如果你需要处理字符串形式的枚举成员,你可以使用 ToString() 方法或者在XAML中使用 x:Static 来获取它们。

用常量代替枚举

在我们需要使用枚举对应的值的时候,我们完全可以使用常量代替。

1
2
3
4
5
6
7
8
9
10
11
12
13
public class ClassDataType
{
public const string START_CLASS = "startclass";
public const string STOP_CLASS = "stopclass";
public const string SAVE_FILE = "savefile";
public const string ASK_TEACHER = "askteacher";
public const string ASK_STUDENT = "askstudent";
public const string SIGN = "sign";
public const string PAPER_TEACHER = "paperteacher";
public const string PAPER_STUDENT = "paperstudent";
public const string VOTE_TEACHER = "voteteacher";
public const string VOTE_STUDENT = "votestudent";
}

在XAML中使用枚举

假设我们有一个 Person 类,其中包含一个 Gender 属性:

1
2
3
4
5
public class Person
{
public string Name { get; set; }
public Gender Gender { get; set; }
}

在XAML中,可以使用 ObjectDataProviderx:Static 来引用枚举:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp"
Title="MainWindow" Height="350" Width="525">

<Window.Resources>
<ObjectDataProvider x:Key="GenderValues" MethodName="GetValues" ObjectType="{x:Type local:Gender}" />
</Window.Resources>

<StackPanel>
<ComboBox ItemsSource="{Binding Source={StaticResource GenderValues}}" SelectedItem="{Binding SelectedGender}" />
</StackPanel>
</Window>

数据绑定

在上述例子中,ObjectDataProvider 提供了枚举值的集合,可以通过数据绑定设置到控件的属性中。

在实际应用中,你可以根据需要调整枚举类型和数据绑定方式来满足特定的场景和要求。

通过这种方式,你可以在WPF应用程序中有效地利用枚举类型来管理和展示数据。