各セクションが静的クラスに対応し、各セクションの値がクラスのプロパティに対応するファイル .ini を C# で読み取る必要があります。私は例を行います:
[Database]
path='test.db'
userid='root'
password=123123
この方法でクラスデータベースを作成しました
public static class DataBase
{
public static string userId;
public static string psw;
public static string path;
}
したがって、[Database] を読むときは、すべてのパラメーターを読み取る必要があり、この名前が Database クラスに存在する場合は、その値を設定する必要があります。
どうすればそれができますか?Reflection を使用する必要があると思いますが、使用できません。
書いたコードを投稿しますが、この行に到達するとelencoProprietàがnullになります。
var elencoProprietà = tipo.GetProperties(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// Program t = new Program();
//t.Run();
var testo = @"[Database]
path='test.db'
userid=12
password=black";
//Ini parser
var parser = new IniParser.Parser.IniDataParser();
var dati = parser.Parse(testo);
string assemblyName = "ConsoleApplication1";
string namespaceName = "ConsoleApplication1";
//Print section count
Console.WriteLine("Section number: " + dati.Sections.Count);
foreach (var sezione in dati.Sections)
{
string fullName = string.Format("{0}.{1}, {2}", namespaceName, sezione.SectionName, assemblyName);
Type tipo = Type.GetType(fullName, throwOnError: false, ignoreCase: true);
Console.WriteLine("\nFull name: {2} \n Section[{1}]Type: {0}", tipo, sezione.SectionName, fullName);
//If tipo is null, it means that the class doesn't exist
//So continue to next section
if (tipo == null)
{
Console.WriteLine("tipo null");
continue;
}
//If class exist, i get his properties
var elencoProprietà = tipo.GetProperties(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
//read all keys
foreach (var chiave in sezione.Keys)
{
Console.WriteLine("Key: " + chiave.KeyName + " Size property list: " + elencoProprietà.Count());
var proprietà = elencoProprietà.FirstOrDefault(p => p.Name.Equals(chiave.KeyName, StringComparison.InvariantCultureIgnoreCase));
//This property doesn't exist
if (proprietà == null)
{
Console.WriteLine("Property is null. " );
continue;
}
//Set the value to the class
var valore = Convert.ChangeType(chiave.Value, proprietà.PropertyType);
proprietà.SetValue(null, valore, null);
Console.WriteLine("Value: {0}", valore);
}
}
Console.ReadLine();
}
}
public static class Predefiniti_DataBase
{
public static string userId;
public static string psw;
public static string path;
}
}