简体   繁体   中英

How to get a class properties using reflection (Assembly)

I have a C# .exe file with different classes.

I need to get a property that is inside a class within the executable file.

Right now Im doing this:

Assembly a = Assembly.LoadFile(servicePath);
            foreach (Type t in a.GetTypes())
            {
                Console.WriteLine(t.Name);
            }

And I can see that the class is write in the console, now how can I get a property of that class, by the way I don't and won't have that class referenced in my project ?

This is my class:

/// <summary>
    /// Summary description for ProjectInstaller.
    /// </summary>
    [RunInstaller(true)]
    public class SyncServiceInstaller : System.Configuration.Install.Installer
    {
        private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
        private System.ServiceProcess.ServiceInstaller serviceInstaller1;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

        public SyncServiceInstaller()
        {
            // This call is required by the Designer.
            InitializeComponent();

        }
}

I need to get this variable within that class: serviceInstaller1

Any clue?

I would start by loading assemblies then filter out assemblies other than what you're looking for, then call GetField("...") , on the resulting assembly. The item you're attempting to retrieve is a field not property.

FieldInfo field = AppDomain.CurrentDomain.GetAssemblies()
                      .FirstOrDefault(n => n.GetType().Equals(typeof(SyncServiceInstaller)))?.GetType()
                      .GetField("serviceInstaller1", BindingFlags.Instance 
                                                     | BindingFlags.Public 
                                                     | BindingFlags.NonPublic);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM