How to automatically determine best .NET type match of a value
I'm working on a T4 template to automatically generate a C# class definition from an XML file. For each element in 开发者_开发问答the XML document I'd like to determine the type of the content in that element. Is there a framework class that handles automatically determining a type from a string value?
That is a very interesting question but I am afraid you are going to have a tough time finding anything in the FCL that will do this.
If you think about it, your problem is a rather unique one, you have a known type as a conversion source and an unknown output type. This doesn't come up too often in day-to-day coding using a framework like .NET.
Since the .NET framework is designed to be used with strongly-typed languages, types are very important and most of the time we know what type we want and can request a conversion from some generic source (like a string or an object) to that specific type. That is why we have casting, conversion methods (like Convert.ToInt32
and such), and similar things. They are all designed to allow us to directly state the output type of the conversion since we know what it is that we want to get.
All that being said, I would be interested to see if someone else has written something like this because the parsing that would be involved in getting this to work must be very similar to the C# compiler itself in the way that literal values are handled in source code.
You might want to take a look at the reflected source of XSD.exe and/or the some of the code in the System.Xml.Serialization.Advanced.SchemaImporterExtension class where you can control some of the advanced serialization stuff. In the past XSD has done a pretty good job of getting a starter schema file generated from a XML file.
精彩评论