美文网首页
2020-07-02 - C#单例

2020-07-02 - C#单例

作者: zdl | 来源:发表于2020-07-02 09:34 被阅读0次

    C#单例模式

    使用懒加载模式创建, 写法比较优雅.
    private static readonly Lazy<T> _instance = new Lazy<T>(
                () =>
                {
                    var ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                    if (ctors.Count() != 1)
                        throw new InvalidOperationException(String.Format("Type {0} must have exactly one constructor.", typeof(T)));
                    var ctor = ctors.SingleOrDefault(c => c.GetParameters().Count() == 0 && c.IsPrivate);
                    if (ctor == null)
                        throw new InvalidOperationException(String.Format("The constructor for {0} must be private and take no parameters.", typeof(T)));
                    return (T)ctor.Invoke(null);
                }
                );
    
            public static T Instance
            {
                get { return _instance.Value; }
            }
    

    相关文章

      网友评论

          本文标题:2020-07-02 - C#单例

          本文链接:https://www.haomeiwen.com/subject/wwdlqktx.html