如何在不初始化或构造对象的情况下从对象获取属性

How to get properties from an object without initializing or constructing the object

听起来不太可能,但我想在注销之前先问一下。

我正在编写一个带有插件系统的应用程序,我想在初始化或构建它之前获取插件中包含的属性class

接口:

public interface IMPlugin
{
    string PluginName { get; }
    string PluginSafeName { get; }
    string PluginDescription { get; }
    Version PluginVersion { get; }
    string PluginAuthorName { get; }

    [DefaultValue(null)]
    string PluginAuthorEmail { get; }

    [DefaultValue(null)]
    string PluginAuthorURL { get; }

    [DefaultValue(false)]
    bool PluginActive { get; set; }
    /// <summary>
    /// Plugin ID issued by InputMapper. Used for updates. </summary>
    int PluginID { get; }
}

插件:

   public class InputMonitor : IMPlugin,ApplicationPlugin
    {
        public string PluginName { get { return "My Plugin"; } }
        public string PluginSafeName { get { return "MyPlugin"; } }
        public string PluginDescription { get { return "My Plugin."; } }
        public Version PluginVersion { get { return new Version("0.1.0.0"); } }
        public string PluginAuthorName { get { return "John Doe"; } }
        public string PluginAuthorEmail { get { return "foo@bar.com"; } }
        public string PluginAuthorURL { get { return ""; } }
        public int PluginID { get { return 0; } }

        public bool PluginActive { get; set; }

        public InputMonitor()
        {

        }
    }

我的问题是我希望我的应用程序能够在初始化之前检索插件信息,以便用户可以随意激活和停用插件,但插件的详细信息仍然可以在插件浏览器中看到。但我不想依赖插件开发人员不在他们的构造函数中做任何事情,只将他们的代码放在其他接口方法中。

是否可以初始化对象并强制忽略其构造函数,或者有什么东西可以一起禁止构造函数?

听起来您的插件应该通过 attributes 而不是通过公开属性来配置:

[Plugin(Name = "My Plugin", SafeName = "MyPlugin" ...)]
public class InputMonitor

您可以通过反射访问属性,而无需创建 class 的实例。

毕竟,这是关于类型的元数据——而不是关于该类型的任何一个实例的信息。

初始化一个 class 和调用它的构造函数是一回事。

要么构建一个插件实例 class 只是为了读取其属性然后将其丢弃。

你还有第二个helper/describerclass。 (我知道你不想要)