我有一个基(抽象)类 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/