Idea for extending C# syntax

你。 提交于 2019-12-03 06:19:15

I won't say whether this is a good idea or not, since I don't know enough about what you're trying to do. I would suggest this, though: What you're proposing is to have some kind of "extended C#" source code file that gets translated into regular cs during the build process.

Personally, I would clarify this by first breaking away from the idea that you are "extending" the C# language; I would instead think of it as defining a new language that happens to be syntactically similar to C# (I assume). Use a different file extension so that Visual Studio does not try to compile your language as C#. (Maybe .csx? People love adding the letter x, right?)

Visual Studio already does this sort of thing in other ways that might not be quite so obvious. If you add a resource file to a project, Visual Studio will typically also include a dynamically generated "designer.cs" with code generated based on the content of your .resx file. If you look at the properties of the .resx file, you'll note that the "Custom Tool" property has a value of "ResXFileCodeGenerator". In theory you should be able to implement your own generator to perform the translation step that you mentioned. In fact, this translation does not have to be a one-time thing as you said. The translation process should generate a new file, but leave the original file intact. Any changes to the original file causes Visual Studio to regenerate the auto-generated file.

I've not tried to implement a custom generator myself, but I think these articles are relevant: Implementing Single File Generators, and Registering Single File Generators

Your .csproj file would contain something such as the following:

<Content Include="Example.csx">
  <Generator>ExtendedCSharpCodeGenerator</Generator>
  <LastGenOutput>Example.cs</LastGenOutput>
</Content>
<Compile Include="Example.cs">
  <AutoGen>True</AutoGen>
  <DesignTime>True</DesignTime>
  <DependentUpon>Example.csx</DependentUpon>
</Compile>

Where Example.csx is the source code file containing your extended syntax and Example.cs is the resulting output of translating Example.csx into normal C# code.

What you are talking about doing seems like a perfect task for T4 templates in Visual Studio.

http://msdn.microsoft.com/en-us/library/bb126445.aspx

You can define anything you'd like; text files with a certain format, UML models, a database; and your T4 template can transform it into code in what ever way you wish.

I'm not sure it's a good idea, but I just had an idea: maybe you can have a look at Extending Visual Studio, download the SDK and check the doc. Maybe it would be possible to do what you are trying to achieve.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!