AppContext详解

以下内容大部分来源官网,包含部分个人理解

好,进入正题

先上结构:

#region 程序集 mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.8\mscorlib.dll
#endregion

namespace System
{
    //
    // 摘要:
    //     提供用于设置和检索应用程序上下文相关数据的成员。
    public static class AppContext
    {
        //
        // 摘要:
        //     获取程序集解析程序用于探测程序集的基目录的路径名。
        //
        // 返回结果:
        //     程序集解析程序用于探测程序集的基目录的路径名。
        public static string BaseDirectory { get; }
        //
        // 摘要:
        //     获取当前应用程序所针对的框架版本的名称。
        //
        // 返回结果:
        //     当前应用程序所针对的框架版本的名称。
        public static string TargetFrameworkName { get; }

        //
        // 摘要:
        //     返回分配给当前应用程序域的已命名数据元素的值。
        //
        // 参数:
        //   name:
        //     数据元素的名称。
        //
        // 返回结果:
        //     如果 name 识别出已命名值,则为 name 的值;否则为 null。
        public static object GetData(string name);
        //
        // 摘要:
        //     设置开关的值。
        //
        // 参数:
        //   switchName:
        //     开关的名称。
        //
        //   isEnabled:
        //     开关的值。
        //
        // 异常:
        //   T:System.ArgumentNullException:
        //     switchName 为 null。
        //
        //   T:System.ArgumentException:
        //     switchName 为 System.String.Empty。
        public static void SetSwitch(string switchName, bool isEnabled);
        //
        // 摘要:
        //     尝试获取开关的值。
        //
        // 参数:
        //   switchName:
        //     开关的名称。
        //
        //   isEnabled:
        //     此方法返回时,如果找到 switchName,则包含 switchName 的值;如果未找到 switchName,则为 false。 此参数未经初始化即被传递。
        //
        // 返回结果:
        //     如果设置了 switchName 且 isEnabled 参数包含开关的值,则为 true;否则为 false。
        //
        // 异常:
        //   T:System.ArgumentNullException:
        //     switchName 为 null。
        //
        //   T:System.ArgumentException:
        //     switchName 为 System.String.Empty。
        public static bool TryGetSwitch(string switchName, out bool isEnabled);
    }
}

解释----提供用于设置和检索应用程序上下文相关数据的成员,

什么是上下文呢?以我的理解是一个资源环境,具体参照我的另一篇博客https://blog.csdn.net/dsadasjdka/article/details/88863066.

官网上的TryGetSwitch和SetSwitch可以用来做一个类似dll版本切换的功能

 public static int SubstringStartsAt(String fullString, String substr)
    {
        bool flag;
        if (AppContext.TryGetSwitch("switchName2", out flag) && flag == true)
            return fullString.IndexOf(substr, StringComparison.Ordinal);
        else
            return fullString.IndexOf(substr, StringComparison.CurrentCulture);
    }

app.config



     
        
    
      
    
  
  
    
    
  

剩下的两个函数

AppDomain.CurrentDomain.SetData("xiaoshi","dddddd");
string a = AppContext.GetData("xiaoshi") as string;

 

你可能感兴趣的:(C#)