简体   繁体   English

C#在类之间传递数据

[英]C# passing data between classes

Just wondering how people would go about this. 只是想知道人们会怎么做。 Say I have one class that creates and populates a Treeview which is then added to a Winform. 假设我有一个类创建并填充Treeview,然后将其添加到Winform。

I have another class that is dependent upon data within the Treeview. 我有另一个依赖于Treeview中数据的类。 So for example, when a user clicks on a specific node in the Treeview, class b needs that information that the node holds so that it can perform some calculation and display the result. 因此,例如,当用户单击Treeview中的特定节点时,类b需要该节点保存的信息,以便它可以执行某些计算并显示结果。

Would it better practise to simply pass a reference to the Treeview to the second class, or just the data that it needs? 简单地将对Treeview的引用传递给第二个类,或者只是将它需要的数据传递给它会更好吗? Or would it be okay to set the Treeview as static and use events so that the new class can access the treeview directly when a node is clicked on? 或者可以将Treeview设置为静态并使用事件,以便新类可以在单击节点时直接访问树视图?

Thanks. 谢谢。

I would raise an event in the class that holds the treeview. 我会在持有树视图的类中引发一个事件。 That is, define a delegate and an event your class has. 也就是说,定义一个委托和您的类具有的事件。 Then the depending class can subscribe to that event and act on the data included in the event. 然后,依赖类可以订阅该事件并对事件中包含的数据进行操作。 As I understand your question the depending class doesn't need to do anything with the treeview and should therefor not know about the treeview. 据我了解你的问题,依赖类不需要对树视图做任何事情,因此不应该知道树视图。

public delegate void YouControlHandler(int relevantData1, string relevantData2);
public class ClassContainingTreeView
{
    public event YouControlHandler TreeViewClickedEvent;
    public void OnTreeViewClicked(object sender, EventArgs)
    {
        // Handle request locally first and extract relevantData1/2
        if(TreeViewClickedEvent != null)
            TreeViewClickedEvent(relevantData1, relevantData2);
    }
}

public class DependingClass
{
     ClassContainingTreeView yourObject = new ClassContainingTreeView();

     public DependingClass()
     {
         yourObject.TreeViewClickedEvent += new YouControlHandler(EventHandler);
     }

     protected void EventHandler(int relevantData1, string relevantData2)
     {
             // Handle event
     }
}

Just pass the data. 只需传递数据。

You do not want a class to be tightly coupled to a UI control. 您不希望类与UI控件紧密耦合。


As an aside, why do you think you need to make the TreeView static in order to consume events from it? 顺便说一下,为什么你认为你需要使TreeView静态以便从中消耗事件?

You can subscribe to an event from objects that are not static. 您可以从非静态对象订阅事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM