问题描述
我是玩弄匿名类型,而我不小心它输出到控制台。它看起来基本上我如何定义它。
I was messing with anonymous types, and I accidentally outputted it onto the console. It looked basically how I defined it.
下面是重现它一个简短的程序:
Here's a short program that reproduces it:
using System;
class Program
{
public static void Main(string[] args)
{
int Integer = 2;
DateTime DateTime = DateTime.Now;
Console.WriteLine(new { Test = 0, Integer, s = DateTime });
Console.ReadKey(true);
}
}
现在,输出的是:
{ Test = 0, Integer = 2, s = 28/05/2013 15:07:19 }
我试着用dotPeek就可以进入装配找出原因,但它并没有帮助这里的dotPeek'd code:
I tried using dotPeek to get into the assembly to find out why, but it was no help. Here's the dotPeek'd code:
// Type: Program
// Assembly: MyProjectName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// Assembly location: Not telling you! :P
using System;
internal class Program
{
public static void Main(string[] args)
{
Console.WriteLine((object) new
{
Test = 0,
Integer = 2,
s = DateTime.Now
});
Console.ReadKey(true);
}
}
所以没有太大的不同,在所有。
So not much different, at all.
那么,它是如何工作的?它是如何输出会这样?
So how does it work? How does it output it like that?
注:
:我忘了打开显示编译器生成的code,这是我没有得到它是如何工作的原因
: I forgot to turn on "Show compiler-generated code", that's the reason I didn't get how it works.
推荐答案
我想补充一些code到HuorSwords答案,编译器会的生成的的ToString
方法为你的榜样,为如下:
Just to add some code to HuorSwords answer, compiler will generate ToString
method for your example, as given below:
public override string ToString()
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("{ Test = ");
stringBuilder.Append((object) this.<Test>__Field);
stringBuilder.Append(", Integer = ");
stringBuilder.Append((object) this.<Integer>__Field);
stringBuilder.Append(", s = ");
stringBuilder.Append((object) this.<s>__Field);
stringBuilder.Append(" }");
return ((object) stringBuilder).ToString();
}
这将是低效的表现在这里使用反射,当你在编译时所需的所有元数据。
It would be performance inefficient to use reflection here, when you have all required metadata at compile time.
使用反编译的 dotPeek ,这取决于使用反编译这个版本可能会有所不同。
Decompiled using dotPeek, this version may vary depending on used decompiler.
请注意:你还反编译与dotPeek,尝试看看的根命名空间的。在那里,你会发现类似的东西:
Note: as you also decompiled with dotPeek, try to look at Root Namespace. There you will find something similar to:
[DebuggerDisplay("\\{ Test = {Test}, Integer = {Integer}, s = {s} }", Type = "<Anonymous Type>")]
internal sealed class <>__AnonymousType0<<Test>
这是什么样的编译一个例子产生,当你定义匿名对象。
This is an example of what the compiled generates, when you define anonymous objects.
这篇关于如何在一个匿名类型的工作做的ToString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!