c# - 不同类别对属性(property)的不同访问

标签 c# access-modifiers

我有一个基(抽象)类 Component .我想控制对派生类属性的访问,以便每个人都可以读取访问权限,但只有某些类允许写入访问权限。

那些“某些类”目前是实现抽象基类的任何东西 MessageHandler<TMessage> .理想情况下,我还想要一个实现 IMessageHandler 的类能够获得访问权限,但我认为这会使要求更加严格。

这将在 xbox 上运行,因此我想避免创建临时对象(例如只读副本)。我还想尽量减少获取读取/写入值的方法调用次数。

Component类和 MessageHandler<TMessage>类目前在它们自己的程序集中,它们都将在使用我的 API 时被其他项目引用。

我猜我将不得不以某种方式改变我的模型,但我无法理解它。

public abstract class Component
{

}

public class DerivedComponentA : Component
{
    int property {get; set;}
}

public abstract class MessageHandler<TMessage>
{

}

public class IntMsghandler : MessageHandler<int>
{
    void DoThing(DerivedComponentA derivedComponentA)
    {
        derivedComponentA.property = 5; // Allowed
    }
}

public class AnyClass // Doesn't inherit MessageHandler, or implement IMessageHandler
{
    void DoThing(DerivedComponentA derivedComponentA)
    {
        derivedComponentA.property = 5; // Not Allowed
    }
}

最佳答案

隔离(基于你提出的问题和我的理解)是基于基类定义(如果有的话)。这意味着隔离应该从它开始。

或者,如果您说,如果某些 class X 实现 MessageHandler 应该能够以多种方式作用于 class Y 类型的对象.在我看来,这意味着两者之间存在着艰难的关系 Y 类MessageHandler

这让我觉得你可以这样做:

  • public get DerivedComponentA
  • 的属性
  • MessageHandler 中定义一个通用的 protected SetProperty(Component compo, string propertyName, object propertyValue) 并使用反射设置所需的属性。

以这种方式在任何 Component 派生类上设置属性的唯一可能方法是使用MessageHandler 方法,因此仅可用对于那些从中得到的人。对于其余可用类型,您 public get(只读)读取数据的权限。

希望这对您有所帮助。

关于c# - 不同类别对属性(property)的不同访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8986370/

相关文章:

java - 使类方法可从程序中的任何位置调用,但不能从程序外部调用

java - 为什么我可以从另一个包访问非公共(public) javax.swing.Box.Filler?

c# - .NET 的 HTML5 WebSockets 客户端

c# - ASP.NET 中每个帐户只能登录一次,不使用内置成员资格

c# - 我应该使用 23 :59:59 or 00:00:00 for 12 AM in 24 hours time format?

C# - 您可以在通用列表中单独循环遍历类型吗?

swift - Swift 4 中的 private 和 fileprivate 有什么区别

c# - 如何使用 Microsoft.Interop.Word 将 excel 文件嵌入到 word 文档中?

Java 默认访问级别(包私有(private)访问)。为什么用它?

class - 为什么我们不能在Kotlin中将类的可见性标记为 “protected”?