正在实施使用自动属性是个好主意单身? [英] Is implementing a singleton using an auto-property a good idea?

查看:156
本文介绍了正在实施使用自动属性是个好主意单身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现了自动属性和他们一样不少。在这一刻,我想我在这里到处都可以使用它们。真的不只是能够到处使用它们,但更要看到他们在大多数情况下如何工作。

I recently found out about auto-properties and like them quite a lot. At this moment I am trying to use them everywhere where I can. Not really to just be able to use them everywhere, but more to see how well they work in most situations.

现在我想提出一个单身,心想:嘿,让我们尝试自动性能在这里一样。

Now I am making a singleton and thought:"Hey, let's try auto-properties here as well".

public class MySingleton
{
    public static MySingleton MySingleton { get; private set; }

    private MySingleton() {}

    static MySingleton() { MySingleton = new MySingleton(); }
}



所以我的问题是:是不是实现一个单一个好主意这样吗?

So my question is: "Is it a good idea to implement a singleton like this?"

我不要求一般单身是否是一个好主意。

I am not asking whether a singleton in general is a good idea.

推荐答案

我也不会亲自做。我不喜欢用带有私人二传手自动实现的属性,你永远不会调用,其中的真正的你想用只读变量支持的只读属性。这只是一个更多的代码行更加明确的关于你的意思:

I wouldn't personally do that. I don't like using automatically implemented properties with a private setter that you never call where really you want a read-only property backed by a read-only variable. It's only one more line of code to be more explicit about what you mean:

public sealed class MySingleton
{
    private static readonly MySingleton mySingleton;
    public static MySingleton MySingleton { get { return mySingleton; } }

    private MySingleton() {}

    static MySingleton() { mySingleton = new MySingleton(); }
}

这方法没人的,甚至的动心的到改变单一类重新分配财产,或变量,因为编译器会阻止他们。他们不得不添加setter和/或使该变量非只读,这是一个较大的变化 - 其中一个希望他们会重新考虑

This way no-one's even tempted to change the singleton class to reassign either the property or the variable, because the compiler will stop them. They'd have to add a setter and/or make the variable non-readonly, which is a bigger change - one which hopefully they'd reconsider.

在换句话说


  • 是的,它会工作

  • 不,我不认为这是一个很好。 。想法

由于C#6,这是具有只读虽然自动实现的属性更容易:

As of C# 6, this is easier with read-only automatically implemented properties though:

public sealed class MySingleton
{
    public static MySingleton MySingleton { get; } = new MySingleton();    
    private MySingleton() {}         
    static MySingleton() {}
}

这篇关于正在实施使用自动属性是个好主意单身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆