gpt4 book ai didi

c# - 如何在 C# 中创建自己的对象,该对象只能具有已定义的有限数量的值,例如像 Haskell 中的 Bools?

转载 作者:行者123 更新时间:2023-12-04 13:31:55 26 4
gpt4 key购买 nike

在 Haskell 中,您可以创建一个新的数据类型,例如如下所示:

Player = Player1 | Player2

在您的代码中,您可以通过键入 Player1 来检查它是 Player1 还是 Player2,而不是像“Player1”这样的奇怪的东西,它必须是一个字符串或检查一个整数。在 C# 中可能有类似的东西吗?我只能想到:

class Player
{
public int CurrentPlayer { get; private set; }
public Player(int plyr)
{
CurrentPlayer = plyr;
}
}

但现在我不能仅使用 thisplayer = Player1 来检查(如果 thisplayer 是玩家)。最终这意味着:如何创建自己的对象,它只能具有已定义的有限数量的值,例如 Bools?

最佳答案

使用Enums :

using System;

public class Program
{
private enum Player { PlayerOne, PlayerTwo }

public static void Main()
{
Player player = Player.PlayerTwo; // Change me between Player.PlayerOne and Player.PlayerTwo to see the output change.
switch(player)
{
case Player.PlayerOne:
//this will get executed
Console.WriteLine("Player is Player One!");
//do stuff
break;

case Player.PlayerTwo:
//this will not get executed
Console.WriteLine("Player is Player Two!");
//do stuff
break;

default:
//this will not get executed
break;
}
}
}

输出:

玩家是玩家二!

See for yourself on .NET Fiddle

关于c# - 如何在 C# 中创建自己的对象,该对象只能具有已定义的有限数量的值,例如像 Haskell 中的 Bools?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64558481/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com