【问题标题】:How to override a static method from a DLL Export如何从 DLL 导出中覆盖静态方法
【发布时间】:2023-03-20 17:54:01
【问题描述】:

我想覆盖 DLL 导出中的静态方法

public class Export {
[DllExport] public static string plugin_name() { return Plugin.Instance.plugin_name(); }
}
    public class Plugin<T> where T: Plugin<T>, new()
    {
        private static readonly Lazy<T> val = new Lazy<T>(() => new T());
        public static T Instance { get { return val.Value; } }

        protected Plugin() { }

        public new static string plugin_name() { }
    }
}

所以现在这些类都在一个 dll 文件中,我希望使用 dll 的人只在主类中这样做。

public class Main : Plugin<Main> {
   public override string plugin_name() { 
       return "a test plugin";
   }
}

我已经测试了几个小时但失败了。

【问题讨论】:

标签: c#


【解决方案1】:

您不能覆盖静态方法。您需要创建一个虚拟或抽象实例方法。

public abstract class Plugin<T> where T : new()
{
    private static readonly Lazy<T> val = new Lazy<T>(() => new T());
    public static T Instance { get { return val.Value; } }

    protected Plugin() { }

    public abstract string plugin_name();
}

public class Main : Plugin<Main> {
    public override string plugin_name() => "a test plugin";
}

plugin_name 方法设为静态也没有多大意义,因为无论如何你都要创建一个单例实例。

您可以查看代码here

【讨论】:

  • 感谢您的回答,我忘记了我需要在 DllExport return Plugin.Instance.plugin_name(); 中返回 plugin_name 问题是我需要 Plugin 中的 类型,但 Main 类不是在 dll 文件中我该如何制作呢?
  • 为什么我使用单例,因为我需要插件中的更多变量用于其他类,例如 Plugin.Instance.ApiVersion 但问题是我不知道如何在没有 的情况下创建一个实例,我只需要制作Plugin.Instance.plugin_name() 可以解决所有问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-27
  • 1970-01-01
相关资源
最近更新 更多