【问题标题】:How to restrict the field not to edit in derived class in c#如何在c#的派生类中限制字段不编辑
【发布时间】:2017-11-23 00:01:29
【问题描述】:

我们如何限制类变量不继承或更改派生类中的值?

前-

Class A
{
   public string name="ABC";
}
Class B:A
{
   //I don't want here name property of base class should be accessible  
     or can be changed  
}

【问题讨论】:

  • 将您的公共字段设为私有
  • 嗨@BhubanShrestha,但不是真正的私有成员可以在派生类中访问
  • 私有成员不能在后代类型中访问,除了使用反射(并且有权这样做),但在这种情况下所有代码都可以使用反射。所以private 就是你想要的。如果“不继承”的意思是“根本看不到该字段”,那么私有就是您想要的。如果您只想限制修改,请创建一个带有公共/受保护 getter 和私有 setter 的属性。
  • 但是,你不能让 B 没有拥有那个字段,它仍然会存在于 B 的内存布局中,因为该字段仍然是从 A 继承的。通过将其设为私有,您将删除对它的访问权限,而不会删除该字段。

标签: c# .net oop inheritance


【解决方案1】:

您可以使用私有集的属性,如下所示:

class A
{ 
    public string Name
     {
       get;
       private set;
     } 
}

class B:A 
{ 
   public B()
    {
      this.Name = "Derived"; // This will not work. If you want to prevent the derived class from accessing the field, just mark the field as private instead of public.
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 2019-11-13
    • 1970-01-01
    • 2019-12-22
    • 2021-02-17
    • 2015-03-31
    相关资源
    最近更新 更多