[翻译]  Generating classes from Anonymous types in C#

[CHINESE]  从C#中的匿名类生成类


Are there any tools that can generate classes from anonymous types?

有没有可以从匿名类型生成类的工具?

I have a complex data structure that I have created using anonymous types. I would like to use this data structure in other places where the anonymous type would be out of scope. That's why I'm looking for such a code generation tool.

我有一个复杂的数据结构,我使用匿名类型创建。我想在匿名类型超出范围的其他地方使用此数据结构。这就是为什么我在寻找这样的代码生成工具。

4 个解决方案

#1


17  

That's one of the refactorings supported by Resharper. With nested anonymous types (where one anonymous type has properties of another anonymous type), you'll just have to convert the inner types before you get the option to convert the outer one.

这是Resharper支持的重构之一。对于嵌套的匿名类型(其中一个匿名类型具有另一个匿名类型的属性),您只需要在获得转换外部类型的选项之前转换内部类型。

#2


21  

I found another way that does this without using Resharper. It is tested on VS 2015.

我发现了另一种不使用Resharper的方法。它在VS 2015上进行了测试。

Suppose you have an anonymous type like this:

假设你有一个这样的匿名类型:

return new
{
    Prop = "val"
};

Just give it a name, like this

只要给它一个名字,就像这样

return new AnonType
{
    Prop = "val"
};

and after that a light bulb appears near the first line and when you click it, it shows you options that will generate this class for you, wherever you want.

然后在第一行附近出现一个灯泡,当你点击它时,它会显示为你生成这个类的选项,无论你想要什么。

Here you can see what am I talking about.

在这里你可以看到我在说什么。

Demonstration

#3


8  

Resharper - Convert Anonymous to Named Type

Resharper - 将匿名转换为命名类型

The Convert Anonymous to Named Type refactoring converts anonymous types to nested or top-level named types in the scope of either the current method (locally) or the whole solution (globally). In the dialog box that this refactoring provides, you can also specify whether ReSharper should generate auto-properties or properties with backing fields, and opt to generate equality and formatting method overrides. enter image description here

将匿名转换为命名类型重构将匿名类型转换为当前方法(本地)或整个解决方案(全局)范围内的嵌套或顶级命名类型。在此重构提供的对话框中,您还可以指定ReSharper是否应生成具有支持字段的自动属性或属性,并选择生成相等和格式化方法覆盖。

#4


0  

CodeRush supports this with it's Name Anonymous Type refactoring.

CodeRush支持它的名称匿名类型重构。


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号