C# 属性与方法,哪个更适合与数据成员交互?

C# 属性与方法,哪个更适合与数据成员交互?,c#,winforms,oop,C#,Winforms,Oop,我正在探索c的概念,想知道哪种方法更适合实现用户与字段的交互:创建属性还是创建公共成员函数。 方法1 方法2: 我投票支持property,它更具可读性,在上下文中更自然请注意,Java没有Properties,所以我们必须在那里实现getBalance、setBalance方法;在C中,我们可以选择: public class Account { private decimal m_Balance; // You don't have to extract GetBalan

我正在探索c的概念,想知道哪种方法更适合实现用户与字段的交互:创建属性还是创建公共成员函数。 方法1

方法2:

我投票支持property,它更具可读性,在上下文中更自然请注意,Java没有Properties,所以我们必须在那里实现getBalance、setBalance方法;在C中,我们可以选择:

public class Account
{
    private decimal m_Balance; 

    // You don't have to extract GetBalance / SetBalance methods;
    // let's have all the logics being incapsulated within the property  
    public decimal Balance {
      get => m_Balance;
      set => m_Balance = value >= 0
        ? value
        : throw new ArgumentOutOfRange(nameof(value)); 
    } 
}

我怀疑你是否应该吞下天平<0箱;抛出异常通常是更好的策略

只要属性返回速度快,就应该使用它们。这就是他们的目的。在第一种方法中,还应删除多余的私有方法:

public class Account
{
    private decimal balance;
    public decimal Balance
    {
        get => balance;
        set
        {
            if (value < 0)
                throw new ArgumentException();
            this.balance = balanceValue;
        }
    }
}
Microsoft在中列出了一些房地产设计指南

简单的Get*和Set*方法有效地被C中的属性替换


属性不应执行可能需要一段时间的操作或启动某些异步操作。

如果在设置该余额时不执行任何特定操作,则只需使用公共十进制余额{get;set;}。否则,它取决于对一组内部字段或其他属性、其他方法调用和创建的对象执行的操作。有时,您会公开一个与现有公共属性具有相同功能的公共方法,但会重载该方法以提供更多功能并同时设置多个字段/属性,从而控制设置相应属性时可能出现的级联效应。很多设计选项。谢谢,酒店设计指南帮助了我。
public class Account
{
    private decimal m_Balance; 

    // You don't have to extract GetBalance / SetBalance methods;
    // let's have all the logics being incapsulated within the property  
    public decimal Balance {
      get => m_Balance;
      set => m_Balance = value >= 0
        ? value
        : throw new ArgumentOutOfRange(nameof(value)); 
    } 
}
public class Account
{
    private decimal balance;
    public decimal Balance
    {
        get => balance;
        set
        {
            if (value < 0)
                throw new ArgumentException();
            this.balance = balanceValue;
        }
    }
}