C# 友元类和 OOP 组合
给定 A 类(包含原始数据集)和 B 类(包含该数据的重新组织版本(GUI 就绪)),我希望使 A 中的原始数据在 B 中可见。
显然,A 类中的原始数据包含在私有成员中。我想通过使用类似于 C++ 友元类方法的方法使该数据在 B 中可见。
我该如何处理这个问题?
谢谢。
Given class A, which contains sets of raw data, and class B, which contains a re-organized version (GUI ready) of that data I would like to make the raw data in A visible in B.
Clearly the raw data in class A is contained in private members. I would like to make that data visible in B though the use of something akin to the C++ friend classes method.
How can I approach this?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
严格来说,您无法定义可以向其公开数据的特定类(或类列表)。但是,您可以使用
internal
访问修饰符而不是private
,这使得成员可用于同一程序集中的任何类。话虽这么说,您应该强烈考虑通过属性而不是字段来公开这些成员(我猜您正计划公开这些成员)。这样做将允许类准确定义如何将该信息公开给其他类,以及当另一个类更改数据时应该发生什么(如果有的话)。
Strictly speaking, you can't define a specific class (or list of classes) that you can expose the data to. You can, however, use the
internal
access modifier instead ofprivate
, which makes the members available to any class in the same assembly.That being said, you should strongly consider exposing these members through properties rather than fields (which is what I'm guessing you're planning on exposing). Doing this will allow the class to define exactly how that information can be exposed to other classes and what--if anything--should happen when another class changes the data.
也许这可能对你有帮助..
May be this might help you..
您可以在程序集中定义这两个字段并将 A 中的字段标记为“内部”。
一种更面向对象的方法是在 A 中提供一组公共方法,通常通过简单的属性来允许访问数据(或数据的子集)。
You could define both in an assembly and mark the fields in A as "internal".
A more OO approach is to provide a set of public methods in A that allow access to the data (or a subset of the data), typically via simple properties.
根据您的结构,您也许能够使用部分类。这意味着数据和 UI 实际上都在同一个类中,但它们位于不同的文件中。
如果这对您不起作用,那么您可以使用内部作用域变量作为替代方案,或者使用 UI 以更通用的方式表示的数据集。
Depending on your structure you may be able to use Partial classes. This would mean that the Data and UI are actually both within the same class, but you have them within different files.
If that doesn't work for you, then you've got internal scoped variables as an alternative or working with Datasets that the UI represents in a more generic manner.
旧方法(双关语)是定义简单的 getvalue() 和 setvalue() 函数来返回该值,这样如果不使用这些值,这些值将变得无法访问函数,在 C# 中,这些函数是称为属性的预定义成员。
另一种方法是,正如其他人在我之前所说的那样,只需使用
internal
修饰符。The old method (pun intended) would be to define simple getvalue() and setvalue() functions to return that value so that these values would become inaccessible without the use of these functions, in C# these functions are predefined members called properties.
The other method is to, as others have stated before me, just use the
internal
modifier.另一种方法是沿着这些思路进行的。请注意,此处的 getter 和 setter 将类 B 指定为键,因此其他类无法访问类 A 的内部状态。
Another approach would be something along these lines. Notice that the getter and setter here specify class B as a key so other classes cannot reach to the inner state of class A.