提问者:小点点

(C#)比较if语句中的枚举


我想比较ifs语句上的一些枚举,这就是我的意思,但这是行不通的。 基本上,我想看看是否受伤是相同的枚举,所以如果,例如,受伤是出血,你需要绷带等,如果你需要任何其他信息,请让我知道。

static string injuries = GetInjuriesName(GetInjuries(closestPlayer));
EPedInjuries result;
if (Enum.TryParse(injuries, out result) && result == EPedInjuries.Overdose)
{
.....
}
else if (Enum.TryParse(injuries, out result) && result == EPedInjuries.GunShotWound)
{
....
}
....


public enum EPedInjuries
{
    OpenFracture,
    GunShotWound,
    Fever,
    BrokenLeg,
    BrokenArm,
    BrokenRib,
    Overdose,
    .....
}

    public static EPedInjuries GetInjuries(Ped ped)
    {
        Ped = ped;
        int num = API.Common.Random.Next(0, 101);
        if (num >= 0 && num <= 37)
        {
            return EPedInjuries.Overdose;
        }
        if (num > 37 && num <= 55)
        {
            return EPedInjuries.GunShotWound;
        }
        if (num > 55 && num <= 72)
        {
            return EPedInjuries.CardiacArrest;
        }
        ....
}


public static string GetInjuriesName(EPedInjuries injuries)
{
    string result = string.Empty;
    switch (injuries)
    {
        case EPedInjuries.Overdose:
            result = "~r~Overdose";
            break;
        case EPedInjuries.GunShotWound:
            result = "~r~Gunshot Wound";
            break;
        case EPedInjuries.CardiacArrest:
            result = "~r~Cardiac Arrest";
            break;
        ....
    }
    return result;
}

共2个答案

匿名用户

您的GetInjuriesName返回的字符串不是正确的枚举值和枚举。TryParse无法分析该字符串,并返回false:

var injuries = GetInjuriesName(EPedInjuries.Overdose);
Console.WriteLine(injuries); //prints "~r~Overdose"
Console.WriteLine(Enum.TryParse(injuries, out EPedInjuries result)); // prints "False"

只需引入两个字段/变量,一个用于名称,一个用于伤害枚举值:

EPedInjuries injury = GetInjuries(closestPlayer)
string injuryName = GetInjuriesName(injury);

并使用第一个来处理逻辑:

if(injury == EPedInjuries.Overdose)
{
    ....
} 
.....

匿名用户

GetJurines方法已经返回要比较的枚举类型。 正如@Johnny Mopp所指出的,您正在获取枚举,并将其转换为某个字符串,然后尝试将其转换回枚举

做就行了

EPedInjuries result = GetInjuries(closestPlayer);
if (result == EPedInjuries.Overdose)
{
.....
}
else if (result == EPedInjuries.GunShotWound)
{
....
}