我怎样才能声明一个空变量?

时间:2017-06-06 11:11:14

标签: c# try-catch var

这是我的代码:

private void button1_Click(object sender, EventArgs e)
    {
        var api = RiotApi.GetInstance("KEY");


        try
        {
            var game = api.GetCurrentGame(RiotSharp.Platform.EUW1, 79200188);
        }

        catch (RiotSharpException ex)
        {
            throw;
        }

        foreach (var player in game.Participants) // Can't find game variable
        {

        }
    }

我不能在我的foreach循环中调用game.Participants,因为我在try语句中初始化游戏。我不能在try语句之外初始化游戏,但是因为这样做我必须给它一个临时值,而我不知道它会是什么样的价值。

有没有办法将变量声明为null?或者可能有不同的方法来解决这个问题?

5 个答案:

答案 0 :(得分:6)

您应该在try-catch阻止之前声明变量,否则它将不会在try-catch阻止之外显示:

TypeOfGame game = null; // declare local variable here
// note that you should provide initial value as well

try
{
   // assigne it here
   game = api.GetCurrentGame(RiotSharp.Platform.EUW1, 79200188);
}
catch (RiotSharpException ex)
{
    // I hope you have some real code here
    throw;
}

// now you can use it 
foreach(var player in game.Participants)
{

}

请注意,您当前的try-catch块除RiotSharpException之外不会捕获任何内容,即使对于该类型的异常,您只需重新抛出它。因此,如果您完全删除try-catch

,则不会有任何改变
var api = RiotApi.GetInstance("KEY");
// if api can be null, then you can use null-propagation operation ?.
var game = api?.GetCurrentGame(RiotSharp.Platform.EUW1, 79200188);
if (game == null) // consider to add null-check
   return;

foreach(var player in game.Participants)
   // ...

进一步阅读:来自C#规范的3.7 Scopes

  

名称的范围是程序文本的区域   可以引用名称声明的实体而不用   名称的资格。范围可以嵌套

特别是

  

•在a中声明的局部变量的范围   local-variable-declaration(第8.5.1节)是其中的块   声明发生。

因此,当您在try-catch块中声明局部变量时,它只能在try-catch块中引用。如果在方法体块中声明局部变量,则可以在方法体范围内和嵌套范围内引用它。

答案 1 :(得分:4)

这样的事情:

private void button1_Click(object sender, EventArgs e)
{
    var api = RiotApi.GetInstance("KEY");

    // if we have api, try get the game
    var game = api != null 
      ? api.GetCurrentGame(RiotSharp.Platform.EUW1, 79200188)
      : null;

    // if we have game, process the players 
    if (game != null)
        foreach (var player in game.Participants) 
        {
            //TODO: put relevant logic here
        }
}

请注意,try {} catch (RiotSharpException ex) {throw;}冗余构造,可以删除

答案 2 :(得分:0)

你可以这样做吗?我不知道您的GetCurrentGame从api返回的类型,所以我只使用GameType作为占位符。

private void button1_Click(object sender, EventArgs e)
{
    var api = RiotApi.GetInstance("KEY");

    GameType game = new GameType();        

    try
    {
        game = api.GetCurrentGame(RiotSharp.Platform.EUW1, 79200188);
    }

    catch (RiotSharpException ex)
    {
        throw;
    }

    if(game == null || !game.Participants.Any()) return;

    foreach (var player in game.Participants) // Can't find game variable
    {

    }
}

答案 3 :(得分:-1)

尝试这样的事情:

var game = (Object)null;

答案 4 :(得分:-2)

string y = null;

var x = y;

这将起作用