【问题标题】:In C# how can I access a variable outside of the scope where it was set?在 C# 中,如何访问设置范围之外的变量?
【发布时间】:2021-05-30 21:27:31
【问题描述】:

我尝试创建一个函数,该函数打开配置文件,读取特定行以获取存储的值,然后将该值返回给调用子。因为我试图在 while 循环之外返回它,所以我得到了一个编译错误。我将如何获取存储值并将其设置为可以在命名空间中的其他地方使用的变量?

public class Functions
{
    public static string GetODVPath()
    {
        //Read stored path of ODV.accdb file
        string fileName = @"C:\Users\" + Environment.UserName + @"\ODV.conf";

        using (StreamReader reader = new StreamReader(fileName))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                //if line length isnt 0 and line starts with [odv] set value of path
                string odvPath = (line.Length != 0 && line.StartsWith("[ODV]")) ? line.Substring(4) : "";
                
            }
            return odvPath();
        }
        

    }
}

【问题讨论】:

  • 你从函数中返回字符串的值。现在,您正试图将调用字符串变量的结果作为函数返回,这可能会引发异常。去掉括号,用合理的默认值在while 之外声明字符串odvPath,这样就可以了。
  • 您要这样的东西吗? string line; string odvPath = string.Empty; while ((line = reader.ReadLine()) != null) { odvPath = (line.Length != 0 && line.StartsWith("[ODV]")) ? line.Substring(4) : ""; } return odvPath;(在这种情况下,三元运算符没用,一个简单的 if 就足够了,但是您是要在找到的第一个处中断,还是取最后一个?)

标签: c# variables scope


【解决方案1】:

这不是你需要的吗?

class YourApp
{
    static void Main(string[] args)
    {
        string odvPath = Functions.GetODVPath();
        // Do whatever you wish with that
    }
} 

public class Functions
{
    public static string GetODVPath()
    {
        string fileName = @"C:\Users\" + Environment.UserName + @"\ODV.conf";
        
        // If you not sure that file always will be at its place
        if (!File.Exists(fileName))
        {
            return string.Empty;
        }

        using (StreamReader reader = new StreamReader(fileName))
        {
            string line;

            while ((line = reader.ReadLine()) != null)
            {            
                if (line.StartsWith("[ODV]")))
                {  
                   return line.Substring(4);
                }            
            }
        }

        return string.Empty;       
    }
}

这种方式方法返回一个值,如果找到,或者空字符串,如果没有。 事实上 Functions 类和它的方法 GetODVPathpublic - 它们可以在命名空间的任何地方调用。

已编辑:line.Length 检查可能会被删除,因为如果 line.StartsWith("[ODV]")true - 无论如何它至少有 4 个字符长度,并且下一个 Substring(4) 调用将只替换找到行的“[ODV]”部分. 还添加了 File.Exists 检查,如果有可能文件不存在,这很有用。

另外,恕我直言,可以使用System.Linq Where 扩展方法进行简化:

public static string GetODVPath()
{ 
    // Changed with SpecialFolder enum 
    string fileName = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\ODV.conf";
        
    // If you not sure that file always will be at its place
    if (!File.Exists(fileName)) // Don't forget to add System.IO reference
    {
        return string.Empty;
    }
    
    // Where filtration looks much simple
    string result = File.ReadAllLines(fileName).Where(line => line.StartsWith("[ODV]")).FirstOrDefault();
    
    // Here is where ternar is in right place :)
    return string.IsNullOrEmpty(result) ? string.Empty : result.Substring(4);
}       

【讨论】:

  • 谢谢!我可以看到我的部分问题是我试图在错误的地方创建函数。我尝试创建一个新的类文件并将其放置在那里。然后我试着把它放在我命名空间的代码块中。我是 C# 的新手,并且一直在使用 VBA,所以非常感谢您的指导。
  • 跟进,在 conf 文件中,我让用户输入 Access 数据库文件的完全限定网络路径。代码返回:“]\\\\fileServerName\\subFolder\\anotherSubFolder\\yetAnotherSubFolder\\odv.accdb” 我怎样才能防止它包含“]\\”?
  • 将 Substring 调用中的 StartIndex 值从 4 更改为 5。string str = "[ODV]FooBar"; string str1 = str.Substring(4); string str2 = str.Substring(5); str1 将产生 "]FooBar"str2 将产生 "FooBar"。请参阅MSDN 了解更多信息。子字符串索引中指定的字符将是新字符串中的第一个字符。此外,您不应删除 "]\\",只删除括号 "]",因为网络路径以双反斜杠 \\Dir1\Dir2 开头,即代码中的 \\\\Dir1\\Dir2\\。
【解决方案2】:

如果你想在外部类中使用这个变量:

class YourApp
{
    static void Main(string[] args)
    {
        var generateOdvPath = new Functions();
        generateOdvPath.GetODVPath();
        string odvPath = generateOdvPath.GeneralOdvPath;
    }
} 

public class Functions
{
    public string GeneralOdvPath { get; set; }
    public void GetODVPath()
    {
        //Read stored path of ODV.accdb file
        string fileName = @"C:\Users\" + Environment.UserName + @"\ODV.conf";

        using (StreamReader reader = new StreamReader(fileName))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                //if line length isnt 0 and line starts with [odv] set value of path
                string odvPath = (line.Length != 0 && line.StartsWith("[ODV]")) ? line.Substring(4) : "";
            }
        }
        GeneralOdvPath = odvPath;
    }
}

删除一个静态词并为您的路径声明一个属性。

【讨论】:

    猜你喜欢
    • 2012-07-16
    • 1970-01-01
    • 2020-08-06
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    相关资源
    最近更新 更多