单例实例比较

Singleton Instance Comparison

我有一个单例 class,如下所示,我在模型中使用它来表示货币类型。

public class CurrencyType
{
    public int Value { get; set; }
    public string Name { get; set; }
    public string Text { get; set; }

    public static CurrencyType USD => new CurrencyType(1, "USD", "USD");
    public static CurrencyType EUR => new CurrencyType(2, "EUR", "EUR");
    public static CurrencyType GBP => new CurrencyType(3, "GBP", "GBP");

    public CurrencyType(int value, string name, string text)
    {
        Value = value;
        Name = name;
        Text = text;
    }

    public static CurrencyType GetInstance(string name)
    {
        return CurrencyTypes.Single(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));
    }

    public static List<CurrencyType> CurrencyTypes = new List<CurrencyType>
    {
        USD,
        EUR,
        GBP
    };

    public CurrencyType()
    {
    }
}

我想 CurrencyType.GBP 应该与 CurrencyType.GetInstance("GBP") 完全相同,因为它 returns GBP 来自单例列表。

然而 CurrencyType.GBP == CurrencyType.GetInstance("GBP") returns 错误。这是什么原因,我是不是漏掉了一个关键点?

public static CurrencyType USD => new CurrencyType(1, "USD", "USD");
public static CurrencyType EUR => new CurrencyType(2, "EUR", "EUR");
public static CurrencyType GBP => new CurrencyType(3, "GBP", "GBP");

解决方法:将“=>”替换为“=”。

原因:“=>”在本例中是属性getter属性的缩写。 属性 幕后是一个方法,由于“新”运算符,它在被调用时将 return 始终是 CurrencyType 的新实例。