Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#抽象属性,可以在构造函数中初始化,但之后只能读取?_C#_Inheritance - Fatal编程技术网

C#抽象属性,可以在构造函数中初始化,但之后只能读取?

C#抽象属性,可以在构造函数中初始化,但之后只能读取?,c#,inheritance,C#,Inheritance,在一个类中,我有一个属性 protected abstract string test{ get; } 当我尝试在构造函数中初始化它时。我得到一个错误,说: 无法将属性或索引器xxx分配给。-它是只读的 有没有一种方法可以让一些财产 摘要 在ctor中初始化后只读 您可能不需要抽象属性。只有当您想要强制派生类提供自定义实现时,才可以使用它。在您的情况下,您只需要在构造函数中设置它,并将其设置为只读 public abstract class Base { protected strin

在一个类中,我有一个属性

protected abstract string test{ get; }
当我尝试在构造函数中初始化它时。我得到一个错误,说:

无法将属性或索引器xxx分配给。-它是只读的

有没有一种方法可以让一些财产

  • 摘要
  • 在ctor中初始化后只读

  • 您可能不需要
    抽象属性。只有当您想要强制派生类提供自定义实现时,才可以使用它。在您的情况下,您只需要在构造函数中设置它,并将其设置为只读

    public abstract class Base
    {
        protected string MyProperty { get; }
    
        public Base(string myProperty)
        {
            MyProperty = myProperty;
        }
    }
    
    public class Derived : Base
    {
        public Derived()
            : base("DefaultValue")
        { }
    }
    

    你能解释一下你为什么想要这个东西吗?抽象属性的概念是,您可以在派生类中更改其值;只读属性的概念是它不能更改。这些似乎是相反的。您的用例是什么?我们希望在派生类ctor中传递一个字符串以覆盖基类值,但在初始化后为常量。那么为什么属性是抽象的?为什么它不仅仅是一个具体的、只读的、非虚拟的财产?@EricLippert是一个很好的建议。对于我的用例,您的建议将使我绕过上述要求。太棒了!