代码之家  ›  专栏  ›  技术社区  ›  Thomas Flinkow

为什么属性成员需要公开?

  •  1
  • Thomas Flinkow  · 技术社区  · 7 年前

    问题

    正在尝试使用属性

    internal class FooAttribute : Attribute
    {
        internal string Bar { get; set; }
    }
    

    这样地

    [Foo(Bar = "hello world")]
    public class MyOtherClass { }
    

    (在同一个集合中)产生

    错误CS0617:“bar”不是有效的命名属性参数。命名属性参数必须是非只读、静态或常量的字段,或者是非静态的公共读写属性。

    但是,我可以很好地进入 Bar “在代码中” ,例如

    FooAttribute attribute = new FooAttribute { Bar = "hello world" };
    

    解决方案

    但是,如果我将属性更改为

    internal class FooAttribute : Attribute
    {
        public string Bar { get; set; }
        ^^^^^^
    }
    

    我可以按计划使用它。 请注意,我只需要在房产上做标记 public -也不是属性本身。这“解决”了这个问题,尽管 有效地 不会改变 酒吧 .


    为什么属性在这种情况下是“特殊的”—为什么编译器要求它们的字段是公共的?

    这个 documentation on the error 没有提到 为什么? 他们也需要公开。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Jon Hanna    7 年前

    [Foo(Bar = "hello world")] Bar