繁体   English   中英

如何声明一个空变量?

[英]How can I declare an empty variable?

这是我的代码:

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
        {

        }
    }

我无法调用game.foreach循环中的参与者,因为我在try语句中初始化了游戏。 我也不能在try语句之外初始化游戏,因为要做到这一点,我必须给它一个临时值,而我不知道它将是什么样的值。

有没有办法将变量声明为null? 还是有可能以其他方式解决此问题?

你应该声明前变量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)
   // ...

进一步阅读: 3.7 C#规范的范围

名称的范围是程序文本的区域,在其中可以引用名称声明的实体,而无需对该名称进行限定。 范围可以嵌套

特别是

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

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

像这样:

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;}多余的结构,可以删除

你能做这样的事情吗? 我不知道您的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
    {

    }
}

尝试这样的事情:

var game = (Object)null;

字符串y = null;

var x = y;

这会工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM