繁体   English   中英

如何在 switch 语句中使用 AppSetting 字符串

[英]How to use AppSetting string in switch statement

如何使用 switch 语句实现以下相同,

public static string GetPathWithPrefix(string path)
{
    string pathWithPrefox = string.Empty;
    if(path == ConfigurationManager.AppSettings["path1"])
    {
        pathWithPefix = ConfigurationManager.AppSettings["path1WithPrefix"];
    }
    else if(path == ConfigurationManager.AppSettings["path2"])
    {
        pathWithPefix = ConfigurationManager.AppSettings["path2WithPrefix"];
    }
    else if(path == ConfigurationManager.AppSettings["path3"])
    {
        pathWithPefix = ConfigurationManager.AppSettings["path3WithPrefix"];
    }
    return pathWithPefix;
}

在切换时使用ConfigurationManager.AppSettings["path1"]时出现编译错误。

  1. 将映射存储在适当的数据结构中
static readonly ImmutableDictionary<string, string> mapping = new Dictionary<string, string>
{
    { "path1", "path1WithPrefix"},
    { "path2", "path2WithPrefix"},
    { "path3", "path3WithPrefix"},
}.ToImmutableDictionary();
  1. 通过简单的查找使用数据结构
public static string GetPathWithPrefix(string path)
{
    if (!mapping.ContainsKey(path))
        throw new InvalidOperationException("Provided path is unknown");

    return ConfigurationManager.AppSettings[mapping[path]];
}

您需要为路径创建 const 变量,然后您可以在 switch case 中使用该变量。

根据例子:

public class HelloWorld
{
    public const string path1 = "test1";// ConfigurationManager.AppSettings["path1"];
    public const string path2 = "test2";// ConfigurationManager.AppSettings["path2"];
    public const string path3 = "test3";// ConfigurationManager.AppSettings["path3"];
    public static void Main(string[] args)
    {
        Console.Write(GetPathWithPrefix("test1"));
    }

    public static string GetPathWithPrefix(string path)
    {
            string pathWithPefix = string.Empty; 
            switch(path){
              case path1: 
                pathWithPefix = "t1";//ConfigurationManager.AppSettings["path1WithPrefix"];
                break;
              case path2: 
                pathWithPefix = "t2";//ConfigurationManager.AppSettings["path2WithPrefix"];
                break;
              case path3: 
                pathWithPefix = "t3";//ConfigurationManager.AppSettings["path3WithPrefix"];
                break;
            }
         
            return pathWithPefix;
        }
}

switch 语句与大型 if-else 语句不同。

每个案例都必须是唯一的,并且是静态评估的。 无论您有多少案例,switch 语句都会执行一个恒定时间分支。

也请检查一下。 C# switch 语句限制 - 为什么?

暂无
暂无

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

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