类只能由“父级”写入类,但可以被其他类读取
我正在使用 C#,我没有太多经验(到目前为止我主要使用 java/php/javascript)
我想要的是一个保存一些数据的类,这些数据只能是由另一类编写,但仍可以被程序中的其他类读取。
像这样的事情:
public class DataObtainer{
DataItem[] Items;
public DataObtainer(){
Items = new DataItem[20];
}
public void Update(){
Items[0].SomeProperty = 5;//Being able to change SomeProperty
}
//Class only contains properties
public class DataItem{
public int SomeProperty;
}
}
public class AnyOtherClass{
public void SomeMethod(){
DataObtainer do = new DataObtainer();
//What I want:
DataItem di = do.items[0];
Console.WriteLine(di.SomeProperty);//Being able to read SomeProperty
di.SomeProperty = 5;//Not allow this, not being able to change SomeProperty
}
}
I'm using C#, with which I don't have a lot of experience (I've mostly worked with java/php/javascript so far)
What I want is a class in which I save some data, this data can only be written by one other class, but still be read by other classes in the program.
Something like this:
public class DataObtainer{
DataItem[] Items;
public DataObtainer(){
Items = new DataItem[20];
}
public void Update(){
Items[0].SomeProperty = 5;//Being able to change SomeProperty
}
//Class only contains properties
public class DataItem{
public int SomeProperty;
}
}
public class AnyOtherClass{
public void SomeMethod(){
DataObtainer do = new DataObtainer();
//What I want:
DataItem di = do.items[0];
Console.WriteLine(di.SomeProperty);//Being able to read SomeProperty
di.SomeProperty = 5;//Not allow this, not being able to change SomeProperty
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用接口。
说明:
Use an interface.
Explaination:
您应该将
DataItem
设为外部(非嵌套)抽象
类,然后创建一个继承它并提供公共变异器方法的内部(私有)类。在
DataObtainer
中,您可以将对象强制转换为私有继承类并修改它们。You should make
DataItem
an outer (non-nested)abstract
class, then make an inner (private) class that inherits it and provides public mutator methods.In
DataObtainer
, you can then cast the objects to the private inherited class and modify them.这种设计对我来说似乎很尴尬。您可以控制代码,因此除非您正在设计某种框架/API,否则您要求做的事情并不是真正必要的。如果类不应该能够修改属性,则不要修改该属性或不提供 setter。
也许您可以多解释一下您需要完成此任务的内容或原因,以帮助我们了解为您提供实现目标的最佳方法。
使用基本继承的简单示例
That sort of design seems awkward to me. You are in control of the code, so what you are asking to do is not really necessary unless you are designing some sort of framework/api. If a class shouldn't be able to modify a property, don't modify the property or don't provide a setter.
Maybe if you can explain a bit more of what or why you need to accomplish this to help us understand the best approach to provide you for your goal here.
Simple Example using basic inheritance