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

如何处理property.set和.get?

  •  0
  • Kjara  · 技术社区  · 7 年前

    我有一个接口

    public interface IIntf { string Foo { get; set; } }
    

    还有一节课

    class MyClass : IIntf
    {
        public string Foo { get; private set; }
    }
    

    . 现在我得到了编译器错误

    “MyClass.Foo.set”不是公共的。

    Foo.set 是它自己的实体(和 Foo.get 我能对他们做些什么吗?如果是,什么?

    例如,我尝试使用 -它甚至是由VisualStudio提出的

    enter image description here

    但是我没有发现任何有效的语法。当遵循建议并尝试实施 方法(没有相应的 get 因为我已经有了),我得到了一个不同类型的编译器错误:

    enter image description here

    Foo.set 和 福格特

    2 回复  |  直到 7 年前
        1
  •  3
  •   mjwills Myles McDonnell    7 年前

    处理@Kjara在评论中提出的问题:

    1. 属性是使用 get 和 set methods 场景(由编译器完成)。
    2. 你不容易 access /传递这些 方法(无 reflection ).
    3. 定义 得到 设置 同时(您不能定义 在一条线上和另一条线上 另一方面)。
    4. 根据上面的@FrankM和@Dirk,这里的混淆似乎源于这样一个事实:IDE暗示(错误地)您可以分别定义getter和setter。
        2
  •  -2
  •   Wanton    7 年前

    public class MyClass : IIntf
    {
        public string Foo { get; private set; }
        string IIntf.Foo { get => Foo; set => Foo = value; }
    }