【问题标题】:Alternative for the lamda (=>) syntax on properties in C# 4?C# 4 中属性的 lamda (=>) 语法的替代方案?
【发布时间】:2018-07-16 09:14:59
【问题描述】:

例如,我想拥有以下课程(用较新的 c# 版本编写):

public class Database
{
    static Lazy<Database> _instance = new Lazy<Database>(() => new Database());
    public static Database Instance => _instance.Value;
    private string connectionString = "";
    public SqlConnection Connection => new SqlConnection(connectionString);
}

如何在 C# 版本 4 中执行此操作?

【问题讨论】:

  • 试试public static Database Instance { get { return _instance.Value; } }public SqlConnection Connection { get { return new SqlConnection(connectionString); } }
  • 大卫,我已将您的问题重新命名。我想这就是你想要的。如果这不是您的意思,请回滚。
  • 谢谢 :) 没关系@Mafii
  • 天哪,我真笨,我才意识到 => 是 get property xD 的简写形式
  • @DavidWalser 请阅读我更新的答案!顺便说一句,这些被称为表达式主体属性。

标签: c# c#-4.0 static singleton


【解决方案1】:

哦,我好像误会你了!

=&gt; 符号用于返回值(在属性的上下文中,它也称为表达式体属性)。这是 get 语法的快捷方式:

public int Test => 1;

等于

public int Test { get { return 1; } }

原始问题/答案:

你使用匿名方法:

new Lazy<Database>(delegate() { return new Database() });

行为与

相同
new Lazy<Database>(() => new Database());

您可以在这里阅读更多内容:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/anonymous-methods

【讨论】:

    猜你喜欢
    • 2010-11-13
    • 2013-07-09
    • 1970-01-01
    • 2018-01-31
    • 2011-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    相关资源
    最近更新 更多