代码之家  ›  专栏  ›  技术社区  ›  techno

获取和设置返回空属性的字符串属性

  •  -2
  • techno  · 技术社区  · 6 年前

    我正在尝试使用以下代码获取和设置属性。 但是,当尝试使用控制台打印属性时,它返回一个空字符串。为什么不设置该属性?

    using System;
    
    public class Program
    {
        public static void Main()
        {
            myclass x=new myclass();
            x.myproperty="test";
            Console.WriteLine(x.myproperty);
        }
         class myclass{
            string sample;
            public string myproperty
            {
                get { return sample;}
                set {sample=myproperty;}
            }
        }
    }
    
    2 回复  |  直到 6 年前
        1
  •  4
  •   hessam hedieh    6 年前

    在setter中应该使用 value 为基础字段指定新值
    用这个代替

    public string myproperty
    {
        get { return sample; }
        set { sample = value; }
    }
    

    或在C 7中

    public string myproperty
    {
        get => sample; 
        set => sample = value; 
    }
    

    编辑

    如@bradbury9所述,您还可以使用 auto-implemented properties 当然,如果您不想在 getter setter 不仅仅是获取和设置字段,如果是这种情况,您可以使用下面的代码片段

     public string myproperty { get; set; }
    
        2
  •  0
  •   Varun Setia    6 年前

    值关键字对于设置值很重要。在Visual Studio中,可以使用Propfull+Double选项卡来避免此类常见错误。它将通过快捷方式创建完整的属性。

    这是解决方案

        public static void Main()
        {
            myclass x = new myclass();
            x.myproperty = "test";
            Console.WriteLine(x.myproperty);
        }
        class myclass
        {
            string sample;
            public string myproperty
            {
                get { return sample; }
                set { sample = value; }
            }
        }