名称pet在当前上下文中不存在 [英] The name pet does not exists in the current context

查看:80
本文介绍了名称pet在当前上下文中不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行此代码时,我得到的是

When i run this code all i get is

the name pet does not exists in the current context





我正在按照本教程 s [< a href =https://www.dotnetperls.com/enum-parsetarget =_ blanktitle =新窗口> ^ ]一步一步确定发生了什么。







and i am following this tutorial s[^] step by step not sure what is going on .


using System;

class Program
{
    enum PetType
    {
        None,
        Cat = 1,
        Dog = 2
    }

    static void Main()
    {
        // A.
        // Possible user input:
        string value = "Dogfff";

        // B.
        // Try to convert the string to an enum:



        try { PetType pet = (PetType)Enum.Parse(typeof(PetType), value); }

        catch (Exception ex)
        {

            Console.WriteLine(ex.Message);


            pet = PetType.None;
        }

        // C.
        // See if the conversion succeeded:
        if (pet == PetType.Dog)
        {
            Console.WriteLine("Equals dog.");
        }
    }
}





我尝试了什么:



********************************** **************

*

*

********** ************************************************** ************************************************** *****



What I have tried:

************************************************
*
*
*******************************************************************************************************************

推荐答案

正如 Suvendu Shekhar Giri 已经指出的那样,你的 PetType 实例,即 pet 是坏的范围:它可以在try块内部访问。

你必须在try块之前声明它在try块本身内实例化它。

As Suvendu Shekhar Giri already pointed out, your PetType instance, namely pet is bad scoped: it is accessible just inside the try block.
You have to declare it before the try block and the instantiate it inside the try block itself.
PetType pet;
try
{
   pet = ...





请参阅: Microsoft .NET中的变量和方法范围 [ ^ ]。



[更新]

已修复,感谢 Richard

[/ update]


这篇关于名称pet在当前上下文中不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆