简体   繁体   中英

Is it Possible to Create New Classes on RunTime C#

Hi is it possible to Create New Classes in C#,classes which the Application Read's from XML and Declare they're Attributes also reading from XML. like:

<item id=1>
 <Name>John</Name>
 <Surname>Kennedy</Surname>
 <Age>24</Age>
</item>

bests.

Yes it is with System.Reflection.Emit namespace.

But in .net 4.0 you can use dynamic keywoard for this. Like this http://blogs.msdn.com/b/mcsuksoldev/archive/2010/02/04/dynamic-xml-reader-with-c-and-net-4-0.aspx

without dynamic, even if you create new class, you will need reflection to access their properties

Yes it is.

Here you can find how to.

But instead of this you can also store this structure in a Map, where the key is and id and value is a other map that store the properties where key is the name and values is the value.

You can deserialize this XML in a new class: Try something like this:

 public static T DeserializeObject<T>(string filePath)
   {
       XmlDocument doc = new XmlDocument();
       doc.Load(filePath);
       XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);
       XmlSerializer ser = new XmlSerializer(typeof(T));
       object obj = ser.Deserialize(reader);

       return (T)obj;
   }

You have to use Reflection api for doing that which is a complicated thing. Please describe your scenario. Maybe there are simpler approaches.

I doesn't really make sense to. Since C# is strongly typed, you're not going to know at compile type what the object looks like, so you're not going to be able to use it.

Maybe you're better off making an object that uses a Dictionary with the key being the node name. Then you can query the dictionary to find what properties it has.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM