简体   繁体   中英

How to dynamically generate C# class at compile time?

For example, I have written a SomeEntity class:

class SomeEntity
{
    public object Content { get; set; }
}

I want my project to automatically generate the code for another class based on the SomeEntity :

class SomeProvider
{
    public SomeEntity GetEntity(object content) => new SomeEntity { Content = content };
}

This is just a simple demo, the logic of real requirements is much more complicated than this.

In my cognition, this is like Protobuf generates the corresponding class according to the .proto file, and the generated class can be correctly recognized by the IDE (the class is generated in obj dir, how to impl it?).

I have tried Fody , but it seems that the injected object cannot be recognized by the IDE.

What is the best technical principle & solution?

With Fody technique when some codes are injected,IDE and compiler would not be aware of it. I recommend Rosyln which is intended to do the exact thing and much more. Take a look at this link https://learn.microsoft.com/en-us/do.net/csharp/roslyn-sdk/source-generators-overview

For comparing different available source code generation for .net here is a good article: https://dominikjeske.github.io/source-generators/

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