简体   繁体   English

如何使用反射获取类属性(Assembly)

[英]How to get a class properties using reflection (Assembly)

I have a C# .exe file with different classes. 我有一个带有不同类的C#.exe文件。

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 ? 而且我可以看到该类是在控制台中编写的,现在如何by the way I don't and won't have that class referenced in my project该类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 我需要在该类中获取此变量: 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. 我将从加载程序集开始,然后滤除所需的程序集,然后在生成的程序集上调用GetField("...") 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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