我有两种形式。在表格 1 中,我有一个 TreeView 。在一种方法中,我获得了已检查的节点列表。
private void CreateListOfCheckedNodes()
{
TreeNodeCollection nodes = TreeData.Nodes;
Int32 EffectedNodes = GetCheckedNodesCount(nodes);
if (EffectedNodes > 0)
{
;//my code
}
}
public int GetCheckedNodesCount(TreeNodeCollection nodes)
{
int CheckedNodesCount = 0;
for (int i = 0; i < nodes.Count; i++)
{
TreeNode node = nodes[i];
if (node.Checked)
{
TreeFieldSet Item = new TreeFieldSet { TreeId = Int32.Parse(node.Tag.ToString()), Title = node.Text };
MyProject.Tree.TreeCheckedNodes.TreeList.Add(Item);
CheckedNodesCount++;
}
if (node.Nodes.Count > 0)
CheckedNodesCount += GetCheckedNodesCount(node.Nodes);
}
return CheckedNodesCount;
}
如何在没有 Form1 的 new 的情况下调用 Form 2 中的方法 CreateListOfCheckedNodes? 有了这个电话:
Tree.TreeSubjects Ts = new Tree.TreeSubjects();
Ts.CreateListOfCheckedNodes();//if CreateListOfCheckedNodes public
我收到错误!
请帮忙!
请您参考如下方法:
将代码移动到一个新的类中,这两种形式都可以访问。
如果方法不使用任何成员变量,您可以将方法设为静态(快速浏览一下代码似乎表明是这种情况)。
static class TreeNodeCollectionHelper
{
public static int GetCheckedNodesCount(TreeNodeCollection nodes)
{
...
}
}
您也可以考虑将其设为 extension method TreeNodeCollection 类,但这应该谨慎进行,因为它可能会让您的同事感到惊讶。
