C#使用Reflection设置静态类的属性值

时间:2016-05-02 22:31:32

标签: c# static-members system.reflection static-class

我必须在C#中读取一个文件.ini,其中每个部分对应一个静态类,每个部分中的值对应于该类的属性。我做了一个例子:

[Database]
path='test.db'
userid='root'
password=123123

我以这种方式创建了一个类数据库

public static class DataBase
    {
        public static string userId;
        public static string psw;
        public static string path;
    }

因此,当我阅读[数据库]时,我必须阅读所有参数,如果这个参数的名称存在于数据库类中,我必须设置他的值。

我怎么能这样做?我想我必须使用Reflection但我不能使用它。

我发布了我写过的代码但是当到达这一行时,elencoProprietà为空。

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;
    }
}

0 个答案:

没有答案