c# - 如何在另一个类中获取单例实例

标签 c#

我想在另一个类中获取 Lazy 实例问题是 T 类型仅在主类中设置

实例所在的第一个类是这样的:

public class singleton<T> where T : class, new()
{
    private readonly static Lazy<T> val = new Lazy<T>(() => new T());
    public static T instance { get { return val.Value; } }

    public int UserID {get;set;} 
}  

现在我有一个用于所有用户数据的其他类

public class User
{ 
    public string Name()
    {
        return data.GetUserFromID(singleton.instance.UserID)
    }
}  

单例不工作,因为我需要参数,但 T 只在主类中

public class main : singleton<main>
{
    public main()
    {
        UserID = 5; 
    }
}

编辑

如何从另一个类中的单例类获取 ID
单例文件

   public class singleton<T> where T : class, new()
    {
        private readonly static Lazy<T> val = new Lazy<T>(() => new T());
        public static T instance { get { return val.Value; } }

        public int UserID {get;set;} 

        private singleton() {
         Datas.UserID = UserID;
        }    
}  

另一个文件

public class Datas {
      public static int UserID {get;set;} 
}

最佳答案

the singleton is not working because I need the Argument but the T is only in the main class

您需要做的就是更改您的代码:

public class User { 
 public string Name() {
  return data.GetUserFromID(singleton.instance.UserID)
 }
}  

...指定通用类型参数:

public class User 
{ 
    public string Name()
    {
        var m = singleton<main>.instance;
        Console.WriteLine($"Inside User.Name, m.UserId = {m.UserID}");
        return "todo";
    }
}  

这是必需的,因为您的客户端代码正在直接访问通用基础。如果您将其封装到工厂管理器或类似工具中,客户就不需要指定类型。

这是一个小测试工具

private void Run()
{
    var x = singleton<main>.instance;
    Console.WriteLine($"x.UserId = {x.UserID}");

    var y = singleton<main>.instance;
    Console.WriteLine($"y.UserId = {y.UserID}");

    x.UserID++;
    Console.WriteLine($"x.UserId = {x.UserID}");
    Console.WriteLine($"y.UserId = {y.UserID}");

    var user = new User();
    Console.WriteLine($"User.Name = {user.Name()}");

    var mp = MissPiggy.Instance;
}

产生以下结果。请注意更改两个不同变量的属性如何修改同一个单例。

enter image description here

在如何实现单例方面也存在一些问题。单例类应该有一个 private 构造函数,它应该是管理生命周期的类,而不是辅助类。

例如

public sealed class MissPiggy
{
    private static Lazy<MissPiggy> _instance = new Lazy<MissPiggy>(() => new MissPiggy());

    private MissPiggy()
    {

    }

    public static MissPiggy Instance
    {
        get { return _instance.Value; }
    }
}

关于c# - 如何在另一个类中获取单例实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56477208/

相关文章:

c# - 在 C# 中解析 HTML 表格

c# - SHGetFileInfo : Description for a files extension too short

c# - System.Security.Cryptography.HMACSHA1 存在于具有相同命名空间的两个程序集中

c# - WCF 4 REST - 用于身份验证的多个标准端点

c# - 调度任务以供将来执行

c# - 通过C#执行多语句MySql

c# - 在保持整体亮度的同时更改位图的色调

c# - 找不到 Xamarin.Forms.Platform.Android.LabelRenderer(xamarin 表单)的构造函数

c# - Int 数组作为字典中的键 VS 字符串

c# - Visual Studio 说 "Method must have a return type"