I'm new to C#. I'm moving from a non-object-oriented website to an object-oriented one. What's the best way to read values from an xml file and/or form values?
I've been using a simple function like this:
public string theTitle() {return Request.Form["title"];}
it works fine until I need to retrieve a bunch of values from the XML files. It seems like a bad practice to set up an xml connection every time I need to retrieve a value -- I have about 10 values to retrieve like this:
public string getTitleFro开发者_运维百科mXML()
{
// set up xml connection and read a bunch of xml values
theTitle = theDataRow["title"].ToString();
return theTitle;
}
So what's the best practice here?
thanks!Gk.
Instead of retrieving data on each get you should be loading up the object as required, then getting the data. A quick and dirty Example
public class MyObject
{
public string Title;
public string AnotherProperty;
public void populateFromForm()
{
Title = Request.Form["Title"];
AnotherProperty = Request.Form["AnotherField"];
}
public void populateFromXML()
{
// set up xml connection and read a bunch of xml values
Title = theDataRow["title"].ToString();
AnotherProperty = theDataRow["AnotherProperty"].ToString();
}
}
Then you would use the above like this:
MyObject formObject = new MyObject();
MyObject xmlObject = new MyObject();
formObject.populateFromForm();
xmlObject.populateFromXML();
string aTitle = formObject.Title;
sting aAproperty = xmlObject.AnotherProperty;
This is a really rough example, you woul be better off using differnt constuctors for each of the scenarios. You would also better off be using private properties with public gettors and settors.
For More info on constructors:
http://www.csharphelp.com/2007/05/c-constructor/
http://msdn.microsoft.com/en-us/library/ace5hbzh.aspx
For more information on private members and getters and setters
http://www.csharp-station.com/Tutorials/Lesson10.aspx
Your page has a Title property. Use that.
精彩评论