c# - 我应该如何在 C# 中使用属性?

标签 c# .net properties

我不确定,因为在 Java 中,getter/setter 看起来有点不同,但是编写这些东西的“c# 方式”是什么?

选项 a.)

    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    private int time;

    public int Time
    {
        get { return time; }
        set { time = value; }
    }

b.)

    private string _name;
    private int _time;

    public string name
    {
        get { return _name; }
        set { _name = value; }
    }

    public int time
    {
        get { return _time; }
        set { _time = value; }
    }

c.)

   public string name {get; set;}
   public int time {get; set;}

好的,有一些例子。什么看起来更好?我应该先写所有私有(private)变量声明然后再写属性还是应该将我的变量和属性声明并排分组。

最佳答案

d 怎么样,遵循 .NET 命名约定:

public string Name { get; set; }
public int Time { get; set; } // Odd type for time, admittedly...

除非你在其中做了一些不平凡的事情,否则不要费心自己手动编写属性。

如果您确实手动编写属性实现,则如何命名私有(private)变量取决于您。我个人会使用:

private string name;
public string Name
{
    get { /* whatever */ }
    set { /* whatever */ }
}

...但如果您想使用下划线,那是您的特权。

至于成员的排序 - 那更是你自己的选择。假设您正在与团队合作,请与团队交谈并了解本地的惯例。

关于c# - 我应该如何在 C# 中使用属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11363334/

相关文章:

c# - 使用 .NET 生成具有给定扩展名的唯一临时文件名

.net - wcf 中的 maxReceivedMessageSize 和流式传输

c# - 在c#中读取cookie

c# - 在 Azure Functions 中使用 NLog

c# - 将对象转换为字节数组

javascript - 像 "__proto__"这样的 javascript 属性名称在 ES5/6 中没有标准化吗?

swift - Swift 3 中的 Depreciation++ 运算符,寻找解决方法

c# - WP 7.5 ShareLinkTask 不在 facebook 中添加缩图

c# - 使用压缩的 .Net DLL 的方法而不将其解压缩到硬盘

java - 私有(private) Java 类属性在方法调用之间神秘地重置