Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3091,56 +3091,3 @@ private static string GuessCachedName(string name)
throw new ArgumentException($"Cannot guess cached field name from switch name '{name}'");
}
}

internal sealed class XmlSerializerAppContextSwitchScope : IDisposable
{
private readonly string _name;
private readonly string _cachedName;
private readonly bool _hadValue;
private readonly bool _originalValue;

public bool OriginalValue => _originalValue;
public bool CurrentValue => AppContext.TryGetSwitch(_name, out bool value) && value;

public XmlSerializerAppContextSwitchScope(string name, bool value, string cachedName = null)
{
_name = name;
_cachedName = cachedName ?? GuessCachedName(name);
_hadValue = AppContext.TryGetSwitch(name, out _originalValue);
AppContext.SetSwitch(name, value);
ClearCachedSwitch(_cachedName);
}

public void Dispose()
{
if (_hadValue)
AppContext.SetSwitch(_name, _originalValue);
else
// There's no "unset", so pick a default or false
AppContext.SetSwitch(_name, false);
ClearCachedSwitch(_cachedName);
}

private static void ClearCachedSwitch(string name)
{
Type t = Type.GetType("System.Xml.LocalAppContextSwitches, System.Private.Xml");
Assert.NotNull(t);

FieldInfo fi = t.GetField(name, BindingFlags.NonPublic | BindingFlags.Static);
Assert.NotNull(fi);
fi.SetValue(null, 0);
}

private static string GuessCachedName(string name)
{
// Switch names are typically of the form "Switch.System.Xml.SomeFeature"
// The cached field is typically "s_someFeature"
int idx = name.LastIndexOf('.');
if (idx > 0 && idx < name.Length - 1)
{
string feature = name.Substring(idx + 1);
return "s_" + char.ToLowerInvariant(feature[0]) + feature.Substring(1);
}
throw new ArgumentException($"Cannot guess cached field name from switch name '{name}'");
}
}