I\'m parsing an XML file with the XmlReader
class in .NET and I thought it would be smart to write a generic parse function to read different attributes generic
You can presumably pass-in, as a parameter, a delegate which will convert from string to T.
Have you tried Convert.ChangeType?
If the method always returns a string, which I find odd, but that's besides the point, then perhaps this changed code would do what you want:
private static T ReadData<T>(XmlReader reader, string value)
{
reader.MoveToAttribute(value);
object readData = reader.ReadContentAsObject();
return (T)Convert.ChangeType(readData, typeof(T));
}
Add a 'class' constraint (or more detailed, like a base class or interface of your exepected T objects):
private static T ReadData<T>(XmlReader reader, string value) where T : class
{
reader.MoveToAttribute(value);
object readData = reader.ReadContentAsObject();
return (T)readData;
}
or where T : IMyInterface
or where T : new()
, etc
try
if (readData is T)
return (T)(object)readData;
First check to see if it can be cast.
if (readData is T) {
return (T)readData;
}
try {
return (T)Convert.ChangeType(readData, typeof(T));
}
catch (InvalidCastException) {
return default(T);
}
Actually, the problem here is the use of ReadContentAsObject. Unfortunately, this method does not live up to its expectations; while it should detect the most appropirate type for the value, it actually returns a string, no matter what(this can be verified using Reflector).
However, in your specific case, you already know the type you want to cast to, therefore i would say you are using the wrong method.
Try using ReadContentAs instead, it's exactly what you need.
private static T ReadData<T>(XmlReader reader, string value)
{
reader.MoveToAttribute(value);
object readData = reader.ReadContentAs(typeof(T), null);
return (T)readData;
}