首页 > 解决方案 > 设置特定的成员访问行为

问题描述

我希望对我的类访问具有特定的行为,尽管有解决方法并且我可以在不实现该特定行为的情况下处理这种情况,但我最终想知道是否有可能在 c# 中实现这一点。

所以我有3个相关的课程:

class Foo {
    public FooData fooData;

  }

  class FooData { //holding Foo class serializable part logic
    public Settings settings;


  }
  // needes to be public along with all its members for serialization
  [Serializable]
  public class Settings { 
    public int { get; set; };
    public int { get; set; };
    public int { get; set; };
  }
}

这 3 个类不一定需要嵌套,而是递归地保存和实例化每个类(希望有意义)。我的意思是,它Foo拥有一个 的领域FooData,并且FooData拥有一个 的领域Settings

我想要的是一种特定的访问行为。这意味着我想从 Foo 访问设置属性,我们称之为“父类” Foo 实例(尽管目前不涉及继承)。但是,如果我处理序列化主题的 Settings 类实例,我希望拒绝访问 Settings 属性(私人行为)。

一些希望可以理解的伪代码:

  //With interfaces, I can expose the settings properties, 
  //so that I can get and set them direclty from the Foo instance. Thants fine
  Foo fooInstance = new Foo();
  fooInstance.int1 = 3; 
  int myInt = FooInstance.int1;

  Foo.Settings mySettings = new Settings();
  mySettings.int1; // ERROR. NO ACCESS FROM SETTINGS INSTANCE. I want this to be private, that you 
  //cannot access it from the settings 
  //instance, only from the Foo instance directly.
  fooInstance.Settings = mySettings; //the whole settings instance needs to be get and set as a 
  //whole, BUT settings variables should ONLY be possible to be accessed from Foo instance.

限制因素是 Settings 类需要是 public,因为对于序列化主题,我需要在任何地方创建它的实例。此外,由于序列化(随处访问),它的所有属性 getter 和 setter 也需要公开。

我的问题是,是否有办法封装 Settings 实例类可访问性以使其及其所有成员公开,以便可以进行序列化,可以限制对设置属性的访问(而不是整个 Settings 实例),这样我就可以从大师班 Foo 获取和设置它们。以便:

fooInstance.int1 = 3; //get or set from foo instance IS granted
fooInstance.settings.int1 = 3; //get or set from foo instance NOT granted

我在类嵌套和接口私有属性暴露等方面尝试了很多东西,但根据我的研究,这是不可能实现的。

总结如果提示是,虽然一个类及其所有成员都需要是公共的(在我的情况下是设置类),但私有行为是否可以在一定程度上针对确定的类或外部世界实现,除了确定的类(需要的序列化类使用权)??(类似于c++朋友类关键字,你可以根据自己的需要进行设置,我猜是需要)。

所有这一切的目的是,来自 Foo 的设置类实例在运行时更改,并且与其他包含可序列化部分的类 Settings 实例具有相似的名称,仅在应用程序保存这些设置时更新。由于在设置实例操作上可能存在类似的名称混淆,我想知道是否可以通过所需的访问控制使代码访问行为尽可能详细以避免错误的实例访问。

我不能发布真正的代码,因为它非常庞大并且包含很多容易引起误解和离题的部分。希望我能理解自己,问题或评论将不胜感激。

我正在考虑的一种解决方法是创建一个平等的设置类,其所有成员都是私有的,并在 foo 类中使用反射或类似的东西设置它(这有什么意义吗?)

尽管扩展和解释复杂,但希望社区中的某个人能找到足够有趣的话题来结束它,并发现这是否可能,如果是,如何,如果不是,要注意c# 的限制。

提前致谢。

标签: c#privatepublicmember-access

解决方案


推荐阅读