How to add metadata to the System.Type?

2020-04-20 03:15发布

问题:

I've been working on a language, but in terms of .NET integration I've only managed to get primitive types working so far. Last night I had a good idea - instead of trying to figure out what the exact System.Type for tuples, modules and functions should be during typechecking, what I could do instead is get the System.Type of System.Object and add some metadata which corresponds to my own complex language types. What matters is not the exact System.Type I would be adding the metadata to, but that each of the stand-ins for the types in my language are distinct from each other.

The reason I need this is that I am using the functions from the reflection namespace for integration which involves juggling System.Types.

type SpiralType =
    | IntT
    | StringT
    | TupleT of SpiralType list

As an example, what I would like to add to the System.Type would be the instances of the above F# discriminated union type in order to ensure uniqueness.

What would be the best way of doing this?

回答1:

A standard way of augmenting type information with extra data in .NET would be to use attributes, though attribute constructor arguments would normally be limited to values you can represent as literals. This may or might not be an issue for you, depending on how rich you would your metadata to be. DU's probably won't work.

Otherwise, a straightforward solution would be to wrap your value together with arbitrary metadata into a generic type, i.e.

type TypeWithMetadata<'typ, 'metadata>(value: 'typ, metadata: 'metadata) = 
    member this.Value = value
    member this.Metadata = metadata

though that might come with an overhead you'd want to avoid?