检测到 C# 无法访问的代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1476438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 17:54:42  来源:igfitidea点击:

C# Unreachable code detected

c#unreachable-code

提问by Jamie

I'm getting a "Unreachable code detected" message in Visual Studio at the point i++ in my code below. Can you spot what I've done wrong?

我在下面的代码中的 i++ 点在 Visual Studio 中收到“检测到无法访问的代码”消息。你能看出我做错了什么吗?

try
{
    RegistryKey OurKey = Registry.CurrentUser;
    OurKey.CreateSubKey("Software\Resources\Shared");
    OurKey = OurKey.OpenSubKey("Software\Resources\Shared", true);
    for (int i = 0; i < cmbPaths.Items.Count; i++) //<---- problem with i
    {
        OurKey.SetValue("paths" + i, cmbPaths.Items[i]);
        break;
    }
}

采纳答案by Juri

The problem is that this actually isn't a loop. You don't have any condition on the break so you could equivalently write something like

问题是这实际上不是一个循环。你在休息时没有任何条件,所以你可以等效地写一些类似的东西

if(cmbPath.Items.Count > 0)
{
   OurKey.SetValue("paths" + 0, cmbPaths.Items[0]);
}

Alternatively you have to correct with something like

或者你必须用类似的东西来纠正

for (int i = 0; i < cmbPaths.Items.Count; i++) 
{
   OurKey.SetValue("paths" + i, cmbPaths.Items[i]);

   if(someConditionHolds)
      break;
}

回答by wefwfwefwe

You're breaking out of the loop before the end of the first iteration.

您在第一次迭代结束之前跳出循环。

回答by Daniel Elliott

The problem is that because you break;in the loop with no chance of it doing anything else, the increment of i (i++) will never be reached.

问题是因为你break;在循环中没有机会做任何其他事情,所以i++永远不会达到i ( )的增量。

回答by NET3

Although your problem is solved i need to tell you this, you can just using the CreateSubKey() method for your purpose. I think It's a better choice. :)

尽管您的问题已解决,但我需要告诉您这一点,您可以仅使用 CreateSubKey() 方法来达到您的目的。我认为这是一个更好的选择。:)

//Creates a new subkey or opens an existing subkey for write access.
var ourKey = Registry.CurrentUser.CreateSubKey("Software\Resources\Shared");

回答by Tom Stickel

You can also end up getting unreachable code if you use say for example Entity Framework, and you didn't add that reference to that project.

如果您使用例如实体框架,并且您没有将该引用添加到该项目,则最终也可能会获得无法访问的代码。

Say you have several projects like A Data Layer Project, a Domain Classes, then you create a console app for testing or whatever and you reference where your dbcontext is at, but if you don't use say nuget and add in EF, you will get code unreachable when trying to write a loop etc...

假设您有多个项目,例如数据层项目、域类,然后您创建一个控制台应用程序进行测试或其他任何内容,并引用 dbcontext 所在的位置,但是如果您不使用 say nuget 并添加 EF,您将尝试编写循环等时获取代码无法访问...