سؤال

This may be way out in left field, crazy, but I just need to ask before I go on implementing this massive set of classes.

Basically, I'm writing a binary message parser that decodes a certain military message format into an object. The problem is that there are literally hundreds of different message types and they share almost nothing in common with each other. So the way I'm planning to implement this is to create hundreds of different objects.

However, even though the message attributes share nothing in common, the method for decoding them is fairly straightforward and follows a pattern. So I'm planning to write a code generator to generate all the objects and the decode logic for each message type.

What would be really sweet is if there was some way to dynamically create an object based on some schema. It doesn't necessarily have to be XML, but XML is pretty easy to work with.

Is this possible in C#?

I would like the interface to look something like this:

var decodedMessage = MessageDecoder.Decode(byteArray);

Where the MessageDecoder figures out what type of message it is and then returns the appropriate object. It will probably return an interface which implements a MessageType Property or something like that.

Basically what I'm wondering is if there is a way to have one object called Message, which implements a MessageType Property. And then Depending on the MessageType, the Message object transforms into whatever type of message it is, so I don't have to spend the time creating all of these message types.

هل كانت مفيدة؟

المحلول

ExpandOobject Where you can dynamically add fields to an object.

A good starting point is here.

نصائح أخرى

Is xsd.exe what you are looking for? It can take an XML file or a schema and generate the c# classes. One problem that you might encounter though is that some of the military message formats are VERY obtuse. You could end up with some very large code files.

Look at T4 templates. They let you write code to generate code, they are integrated into the IDE, and they are quite easy really.

EDIT: There is no way to do what you are after with var, because var requires the right-hand side of the assignment to be statically typed (at compile time). I suppose that you could dynamically generate that statement, then compile and run it, but that's a very painful approach.

If you have XSD's for all of the message types, then you can use xsd.exe as @jle suggests. If not, then I am curious about the following:

// Let's assume this works
var decodedMessage = MessageDecoder.Decode(byteArray);
// Now what?  I don't know what properties there are on decodedMessage, so I cant do anything with it.
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top