如何使用 if 语句创建属性

Nel*_*Dav 4 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;}
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*sch 6

不,但您可以执行以下操作:

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;
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

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

  • 如果是这样,那么@RuardvanElburg 是正确的。您需要使用继承。 (2认同)