如何在try-catch外获取变量x,y和z?
这是我的代码:
public static void mudarSpawn_1(GtaPlayer player, string coordenadas)
{
char[] delimiterChars = { ' ', ',' };
string text = coordenadas;
string[] words = text.Split(delimiterChars);
try
{
float x = float.Parse(words[0], System.Globalization.CultureInfo.InvariantCulture);
float y = float.Parse(words[1], System.Globalization.CultureInfo.InvariantCulture);
float z = float.Parse(words[1], System.Globalization.CultureInfo.InvariantCulture);
}
catch (Exception e)
{
player.SendClientMessage(Color.DarkOrange, "Os valores de x,y e z não foram inseridos de forma correcta, apenas podes usar numeros");
player.SendClientMessage(Color.DarkOrange, "Ex: /mudarspawn3 6321.6 , 96321.38 , 66322.2 ou /mudarspawn3 6321.6 96321.38 66322.2");
}
MSGameMysql.mudarspawn1(x, y, z);
player.SendClientMessage(Color.AliceBlue, "Acabaste de mudar o spawn 1 para: x='" + x + "' y='" + y + "' z='" + z + "'");
}
Run Code Online (Sandbox Code Playgroud)
该
MSGameMysql.mudarspawn1(x, y, z);
player.SendClientMessage(Color.AliceBlue, "Acabaste de mudar o spawn 1 para: x='" + x + "' y='" + y + "' z='" + z + "'");
Run Code Online (Sandbox Code Playgroud)
mudarspawn1()内的这个xy和z变量在x = 0 y = 0且z = 0时返回
我怎样才能解决这个问题?
我试着做一套但得到......但没有幸福的结局.
主要用途是:玩家写/ mudarspawn1 [coordenadas]
例如:/ mudarspawn1 656.32 65.21 698.1
但如果他们使用字符,程序将收到错误,我想向他们发送聊天,告诉他们只能使用数字.
您必须在try范围之前声明并初始化它们:
float x = 0f;
float y = 0f;
float z = 0f;
try
{
x = float.Parse(words[0], System.Globalization.CultureInfo.InvariantCulture);
y = float.Parse(words[1], System.Globalization.CultureInfo.InvariantCulture);
z = float.Parse(words[1], System.Globalization.CultureInfo.InvariantCulture);
}
catch (Exception e)
{
player.SendClientMessage(Color.DarkOrange, "Os valores de x,y e z não foram inseridos de forma correcta, apenas podes usar numeros");
player.SendClientMessage(Color.DarkOrange, "Ex: /mudarspawn3 6321.6 , 96321.38 , 66322.2 ou /mudarspawn3 6321.6 96321.38 66322.2");
}
MSGameMysql.mudarspawn1(x, y, z);
player.SendClientMessage(Color.AliceBlue, "Acabaste de mudar o spawn 1 para: x='" + x + "' y='" + y + "' z='" + z + "'");
Run Code Online (Sandbox Code Playgroud)
但是,您最好float.TryParse()不要在此处查看并且不使用异常处理(这可能会给您带来不希望的结果).例如,
float x;
if (!float.TryParse(words[0], NumberStyles.AllowThousands || NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out x))
{
// unable to parse words[0] as a float, handle it here.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
123 次 |
| 最近记录: |