(no subject)

Aug 12, 2008 15:46

Под катом кусок кода про то, как можно загружать конфиги в с#

Идея в том, чтобы не надо было вручную присваивать все проперти-значения, которые записаны в файле. Достаточно добавить в класс новое свойство и если оно есть в конфиге, то загрузится само.
На универсальность не претендую, писалось сегодня впопыхах и строго под себя. Может кому то идея пригодится.

class GenericWeaponConfig : IWeaponConfig
{
public string WeaponPrereq { get; set; }
public string ResearchPrereq { get; set; }
public string Name { get; set; }
public string CommandIcon { get; set; }

///
/// Automatically loads all values that are public properties of this class. NB! property name should be the same as node name
///
///

public void Load(XmlNode parentNode)
{

var properties = GetType().GetProperties();
foreach (XmlNode node in parentNode.ChildNodes)
foreach (var property in properties)
if (property.Name == node.Name)
SetProperty(property, node);
}

///
/// Converts string to property type if such type is implemented and sets the value
///
///

///

private void SetProperty(PropertyInfo property, XmlNode node)
{
bool converted = true;

switch(property.PropertyType.Name)
{
case "String": property.SetValue(this, node.InnerText, null);
break;

case "Int32":
int iresult;
if (int.TryParse(node.InnerText, NumberStyles.Any, null, out iresult))
property.SetValue(this, iresult, null);
else converted = false; break;

case "Single":
float fresult;
if (float.TryParse(node.InnerText, NumberStyles.Any, null, out fresult))
property.SetValue(this, fresult, null);
else converted = false; break;

default: throw new Exception(string.Format("Type {0} not implemented. ", property.PropertyType));
}

if (!converted) throw new Exception(string.Format("Couldn't convert {2}. Property {0} should be of type {1}. ", property.Name, property.PropertyType, node.InnerText));
}
}_Winnie C++ Colorizer

Previous post Next post
Up