我可以为 C# 中的匿名类指定一个有意义的名称吗?
我们都知道,当我们创建这样的匿名类时:
var Employee = new { ID = 5, Name= "Prashant" };
...在运行时它将是这样的类型:
<>f__AnonymousType0<int,string>
有没有办法为此类类指定一个有意义的名称?
We all know that when we create an anonymous class like this:
var Employee = new { ID = 5, Name= "Prashant" };
...at run time it will be of type:
<>f__AnonymousType0<int,string>
Is there any way to specify a meaningful name to such classes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
这是一种匿名类型,违背了目的。 这些对象被设计为临时的。 天啊,这些属性甚至是只读的。
抱歉,我是个自作聪明的人。 答案是否定的,没有办法告诉编译器匿名类型使用什么名称。
事实上,编译器生成的类型名称在命名中使用非法字符,因此应用程序中不会出现名称冲突。
It's an anonymous type, that defeats the purpose. Those objects are designed to be temporary. Hell, the properties are even read-only.
Sorry, I'm being a smart-ass. The answer is no, there is no way to tell the compiler what name to use for an anonymous type.
In fact, the names of the types generated by the compiler use illegal characters in their naming so that you cannot have a name collision in your application.
然后使用以下语法
Then use the following syntax
实际上,如果您不害怕变得非常具体,您可以使用 TypeBuilder 基于您的匿名类型构建您自己的运行时类型,这将允许您指定类型的名称。 当然,按照本线程中几乎所有其他人的建议,声明一个类要容易得多,但 TypeBuilder 方式更令人兴奋。 ;)
TypeBuilder
Actually, if you're not afraid of getting extremely nitty gritty, you could use TypeBuilder to build your own runtime type based on your anonymous type, which will allow you to specify a name for the type. Of course, it is much easier to just declare a class as almost everyone else in this thread suggested, but the TypeBuilder way is far more exciting. ;)
TypeBuilder
让它成为一个有名字的普通班级吗?
Make it a regular class with a name?
Java 世界中的答案是 本地类(定义于方法),这在 C# 中是不存在的。
The answer in Java World would be a local class (defined in a method), which are absent in C#.
是的,您正在创建一个匿名类,如果您希望您的类有一个名称,即非匿名,则声明一个常规类或结构。
Yes, you are creating an Anonymous Class , if you want your class to have a name, i.e. Not Anonymous, then declare a regular class or struct.
因为它是匿名的,所以你不能说出它的名字。 如果您需要知道类型的名称,那么您必须真正创建一个类。
Since it's anonymous, you cannot name it. If you need to know the name of a type, then you must really create a class.
不,没有办法为您声明的这些类提供有意义的类型名称。 匿名类型就是这样,匿名。 如果不诉诸非常丑陋的黑客手段,就无法显式地“命名”代码中的类型。
如果您确实需要为类型指定名称,则需要显式声明并使用具有所需属性的新类型。
No, there is no way to give a meaningful type name to these classes as you've declared them. Anonymous Types are just that, anonymous. There is no way to explicitly "name" the type in code without resorting to very ugly hacks.
If you really need to give the type a name you will need to explicitly declare and use a new type with the properties you need.
我认为,根据定义,匿名类型不能有名称,只能有编译器赋予的名称。 如果您正在寻找有关匿名类型的更有意义的设计时信息,那么您对编译器的期望过高。
I think that, by definition, Anonymous Types can't have a name, just that which the compiler gives it. If you're looking for more meaningful design-time information on Anonymous Types then you're expecting too much from the compiler.