Andy Lanng
Напишите программу быстрого чтения настроек:
гл.
преобразовано из c# с помощью Преобразователь кода C# в VB и VB в C# – Telerik[^]
Public Class Settings
Private ReadOnly _sectionNameRegex As Regex = New Regex("(?<=\[).*(?=\])")
Private ReadOnly _settingRegex As Regex = New Regex("(?<key>\w+)[^\w]=[^\w](?<value>\w+)")
Private ReadOnly _settings As Dictionary(Of String, Dictionary(Of String, Object))
Public Sub New(ByVal settingsFilePath As String)
Dim settings = File.ReadLines(settingsFilePath)
Dim sectionName = "default"
For Each setting As String In settings
If _sectionNameRegex.IsMatch(setting) Then
sectionName = _sectionNameRegex.Match(setting).Value
If Not _settings.ContainsKey(sectionName) Then
_settings.Add(sectionName, New Dictionary(Of String, Object)())
End If
Else
If _settingRegex.IsMatch(setting) Then
Dim match = _settingRegex.Match(setting)
Dim key = match.Groups("key").Value
Dim value = match.Groups("value").Value
If _settings(sectionName).ContainsKey(key) Then
Throw New InvalidOperationException($"Duplicate key ({key}) found ({sectionName})")
End If
_settings(sectionName).Add(key, value)
End If
End If
Next
End Sub
Public Function GetValueOrDefault(Of T)(ByVal section As String, ByVal key As String) As T
If Not _settings.ContainsKey(section) Then
Throw New KeyNotFoundException(section)
End If
If Not _settings(section).ContainsKey(key) Then
Throw New KeyNotFoundException(key)
End If
Try
Dim result As T = CType(_settings(section)(key), T)
Return result
Catch
Return Nothing
End Try
End Function
End Class
с#
public class Settings
{
private readonly Regex _sectionNameRegex = new Regex(@"(?<=\[).*(?=\])");
private readonly Regex _settingRegex = new Regex(@"(?<key>\w+)[^\w]=[^\w](?<value>\w+)");
private readonly Dictionary<string, Dictionary<string, object>> _settings;
public Settings(string settingsFilePath){
var settings = File.ReadLines(settingsFilePath);
var sectionName = "default";
foreach (string setting in settings){
if (_sectionNameRegex.IsMatch(setting)) {
sectionName = _sectionNameRegex.Match(setting).Value;
if (!_settings.ContainsKey(sectionName)) {
_settings.Add(sectionName, new Dictionary<string, object>());
}
}
else {
if (_settingRegex.IsMatch(setting)) {
var match = _settingRegex.Match(setting);
var key = match.Groups["key"].Value;
var value = match.Groups["value"].Value;
if (_settings[sectionName].ContainsKey(key)) {
throw new InvalidOperationException($"Duplicate key ({key}) found ({sectionName})");
}
_settings[sectionName].Add(key,value);
}
}
}
}
public T GetValueOrDefault<T>(string section, string key) {
if (!_settings.ContainsKey(section)) {
throw new KeyNotFoundException(section);
}
if (!_settings[section].ContainsKey(key)){
throw new KeyNotFoundException(key);
}
try {
T result = (T) _settings[section][key];
return result;
}
catch {
return default(T);
}
}
}