Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

c# - Pass and return ID to method

I need to generate xml file that have unique HEX ID through it. for this I used simple method

public string CalcXML_ID()
        {
            string Return_ID;

            cl_XML_ID = cl_XML_ID + 1;
            Return_ID = cl_XML_ID.ToString("X");

            return Return_ID;
        }

in my main I call this CalcXML_ID three times (I get ID's 1, 2 and 3). Then I call xmlElement method from another class, which needs also to have this unique ID X times. after that I call my CalcXML_ID method again two times. my problem is how to pass the ID to the xmlElement method and getting back the last used ID so that I can continue from there to use the ID for the remaining 2 times. fyi xmlElement return xmlElement as it named.
To make it simple, I have this xml document and node with ID:

XmlDocument doc = new XmlDocument();
XmlElement SW_Blocks_FCNode = doc.CreateElement("SW.Blocks.FB");
SW_Blocks_FCNode.SetAttribute("ID", CalcXML_ID()); //ID return value of 1 here

//ObjectList
XmlNode ObjectListNode = doc.CreateElement("ObjectList");
SW_Blocks_FCNode.AppendChild(ObjectListNode);

then I call the method form other class and pass my ID to it

XmlElement MultilingualTextNode = XML_MultilingualText(doc, "Comment", "", CalcXML_ID()); // The ID used twice inside this method so it should be 2 and 3
ObjectListNode.AppendChild(MultilingualTextNode);

after that I have the following:

XmlElement CompileUnitNode = doc.CreateElement("CompileUnit");
        CompileUnitNode.SetAttribute("ID", CalcXML_ID()); //The ID here has to continue and it should be 4

then I continue my code. the problem is that the ID doesnot continue in the generated file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For this, cl_XML_ID needs to static, you need to have something like this:

public static SomeStaticClass
{
     public static int cl_XML_ID = 0; 

     public static string CalcXML_ID()
        {
            string Return_ID;

            cl_XML_ID = cl_XML_ID + 1;
            Return_ID = cl_XML_ID.ToString("X");

            return Return_ID;
        }

}

Now no matter where you call the method from it will continue to increase cl_XML_ID from the number it was left off.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...