开发者

Sharing class member data between sub components

I have an aggregate 'main' class which contains some data which I wish to share. The main class also has other class members. I want to share the data with these other class members. What is the correct / neatest way to do this?


The specific example I have is as follows. The main class is a .net Form. I have some controls (actually controls within controls) on the main form which need access to the shared data.

Main Form
- DataX
- DataY
- Control1
-- Subcontrol1
- Control2
-- SubControl2

SubControls 1 and 2 both wish to access DataX and DataY.

The trouble is, I feel like better practice (to reduce coupling), would be that either subcont开发者_C百科rols should not know about Main Form, or Main Form should not know about subcontrols - probably the former.

For subcontrols not to know about Main Form, would probably mean Main Form passing references to both Controls 1 and 2, which in turn would pass the references on to SubControls 1 and 2. Lots of lines of code which just forward the references. If I later added DataZ and DataW, and Controls 3 and 4 and SubControls 3 and 4, I'd have to add lots more reference forwarding code.

It seems simpler to me to give SubControls 1 and 2 member references to Main Form. That way, any sub control could just ask for MainForm.DataX or MainForm.DataY and if I ever added new data, I could just access it directly from the sub controls with no hassle. But it still involves setting the 'MainForm' member references every time I add a new Control or Subcontrol. And it gives me a gut feeling of 'wrong'.

As you might be able to tell I'm not happy with either of my solutions. Is there a better way?

Thanks


you could make data x and data y static members so you can access them this works fine if you just have one instance of the main form running

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜