c# - 如何使用 if 语句创建属性

标签 c# if-statement properties

我的问题是,如果可能的话,做这样的事情:

public Class Test
{
  public int Number { get; set; }
  private string text;

  public string Text
  {
    if (Number > 5)
    {
      set {text = value;}
      get {return text;}
    }
  }
}

最佳答案

不,但你可以这样做:

public class Test {
        public int Number { get; set; }
        private string _Text;
        public string Text {
            get {
                if(Number > 5) {
                    return _Text;
                } else {
                    //DEFAULT value here. 
                    return null;
                }                
            }
            set {
                if(Number > 5) {
                    _Text = value;
                } else {
                    //DEFAULT Value. 
                    _Text = null;
                }
            }
        }
    }

如果您使用的是 Visual Studio,我还会查看预处理器指令。根据您尝试使用代码的方式,这些可能更有用。

预处理指令: https://msdn.microsoft.com/en-us/library/3sxhs2ty.aspx

关于c# - 如何使用 if 语句创建属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40595148/

相关文章:

c# - 使用 Roslyn 创建诊断分析器时缺少包

c# - WPF中的嵌套ObservableCollection数据绑定(bind)

c# - 在 C++ 中将一个接口(interface)指针分配给另一个接口(interface)指针

c - 使用 for 循环打印特定的 "non-vowel, vowel, non-vowel"单词

ios - 当 UITextField 的 "editingDidBegin"控件事件触发时,将 UITextField 的当前值设置为属性

java - 属性文件的使用

c# - (读取)文件 I/O 抖动

python - 使用 Python 3 检查 JSON 键是否为空的条件语句

c - 错误 "if not true"- C

python:属性字段是否被自动缓存?