Can I specify a meaningful name for an anonymous class in C#?

Can I specify a meaningful name for an anonymous class in C#?

千纸鹤带着心事 发布于 2021-11-24 字数 327 浏览 865 回复 10 原文

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?

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。

扫码加入群聊

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

葵雨 2022-06-07 10 楼

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.

蒲公英的约定 2022-06-07 9 楼

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.

仅此而已 2022-06-07 8 楼

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.

沫雨熙 2022-06-07 7 楼

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.

如日中天 2022-06-07 6 楼

The answer in Java World would be a local class (defined in a method), which are absent in C#.

小忆控 2022-06-07 5 楼

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

雪花飘飘的天空 2022-06-07 4 楼

Make it a regular class with a name?

public class Employee
{
    public int ID;
    public string Name;
}


var Employee = new Employee { ID = 5, Name= "Prashant" };
枫以 2022-06-07 3 楼
public class Employee {
    public int ID { get; set; }
    public string Name { get; set; }
}

Then use the following syntax

var employee = new Employee { ID = 5, Name = "Prashant" };
芯好空 2022-06-07 2 楼

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.

蝶舞 2022-06-07 1 楼
public class Employee {}