C # Object Metadata

Is it possible to stick metadata to an object in C #?

Context: Framework that sends messages between peers over a network. Messages can be arbitrary .NET serializable custom types.

Of course, when a message is sent by a peer, the infrastructure can wrap the object in the Message class, which stores metadata, and the receiver can expand it. However, the peer processing method may decide to resend the message to another partner โ€” however, I want to keep the original metadata. The user should not use Message.RealMessage all the time, unless re-sending.

I thought about keeping the wrapped instance in the dictionary and retrying the search if there is already a wrapped instance in the dictionary and resending this message, however, since the messages may not occur at all (or repeatedly), it will require more and more memory.

Any solutions? Maybe C # directly supports bonding additional information to an object? Usually I would go to the internal interface, but the user would have to derive all of his classes from the base class of the framework, which is impossible.

Edit: I kind of want to say "here is the WrappedMessage object, but you are allowed to use the interface provided by the T class."

+4
source share
1 answer

There is a ConditionalWeakTable that should do what you want a little better than using a dictionary.

Quote:

Allows compilers to dynamically attach object fields to managed objects.

You can ignore the part related to the class for the compiler :-)

+2
source

Source: https://habr.com/ru/post/1500033/


All Articles