从单例实例获取设置为空

时间:2019-06-06 19:30:11

标签: c#

我目前正在编程一个api,该api是我想用C#编写的c ++插件,实际上api已经差不多完成了,只有当我遇到一个困扰我几个小时的问题时

问题如下

 // this class is in the api dll file
    public class SingleData
    {
        public static Lazy<SingleData> val = new Lazy<SingleData>(() => new IPlugin());
        public static IPlugin Instance { get { return val.Value; } }

        protected SingleData() { }

        public string Author { get; set; }
        public string Name { get; set; }

        public virtual void plugin_getUser(UserData user) { }
    }    

    // this class is also in the api dll file
    public class DllExport { 
        [DllExport] public static void plugin_getUser(UserData user) { return SingleData.Instance.plugin_getUser(user); }
     }

    // this is NOT in the dll file 
    // I want that people who use my API only make it like this
    public class Main : SingleData {
        public Main() {
           Author = "Hans";
           Name = "test plugin";
        }
        public override void plugin_getUser(UserData user) { 
           Console.WriteLine(user.OnlineTime);
        }    
    }

现在的问题是,如果我删除单身人士,则无法在DllExport类中使用return SingleData.Instance.plugin_getUser AuthorName变量为空。

我现在有一些问题,如何在DllExport类中不必键入return SingleData.instance.plugin_getUser的情况下在Main类中花费事件

另一个问题是,我该如何做不同,但是主类应该与我指定的相同

1 个答案:

答案 0 :(得分:0)

我认为您可能需要考虑strangely recurring pattern

    public class SingleData<T> where T : SingleData<T>, new()
    {
        public static Lazy<T> val = new Lazy<T>(() => new T());
        public static IPlugin Instance { get { return val.Value; } }

        protected SingleData() { }

        public string Author { get; set; }
        public string Name { get; set; }

        public virtual void plugin_getUser(UserData user) { }
    }    

    // this class is also in the api dll file
    public class DllExport
    { 
        [DllExport]
        public static void plugin_getUser(UserData user) { return SingleData<Main>.Instance.plugin_getUser(user); }
     }

用法

    public class Main : SingleData<Main>
    {
        public Main()
        {
           Author = "Hans";
           Name = "test plugin";
        }

        public override void plugin_getUser(UserData user)
        { 
           Console.WriteLine(user.OnlineTime);
        }    
    }