我用C#进行了实验,首先创建了一个名为“ ClassLibrary1”的类库,其代码如下:
public class ClassLibrary1
{
public static void f()
{
var m = new { m_s = "abc", m_l = 2L };
Console.WriteLine(m.GetType());
}
}
注意,我删除了IDE生成的名称空间信息.
然后我用下面的代码创建了控制台应用程序:(还删除了名称空间)
在引用ClassLibrary1时:
class Program
{
static void Main()
{
var m = new {m_s = "xyz", m_l = 5L};
Console.WriteLine(m.GetType());
ClassLibrary1.f();
}
}
我运行程序,它打印:
<>f__AnonymousType0`2[System.String,System.Int64]
<>f__AnonymousType0`2[System.String,System.Int64]
Press any key to continue . . .
输出表明在类库和控制台应用程序中定义的2个匿名类具有相同的类类型.
我的问题是:C#二进制如何为它包含的所有类存储其类型信息?如果将其存储在全局位置,则使用dll引用构建exe时,将存在2个相同的匿名类型信息,因此
(1) Is name duplication an error that should be avoid?
(2) If not an error like I tested, how could C# binary store duplicate type information?
(3) And in runtime, what's the rule to look up type information to create real objects?
在我的示例中似乎有些混乱.
谢谢.
解决方法:
I removed namespace information
不相关.程序集的匿名类型在相同的名称空间(即空名称空间)中生成.
此外,请参见C#规范7.6.10.6匿名对象创建表达式:
Within the same program, two anonymous object initializers that specify a sequence of properties of the same names and compile-time types in the same order will produce instances of the same anonymous type.
令人困惑的是,“程序”在这里是指“汇编”.所以:
how does C# binary store its type information for all the classes it contains? If it’s stored in a global place, when the exe is built with dll reference, 2 same anonymous type information is there
是的,但是每个程序集的类型都是唯一的.它们可以具有相同的类型名称,因为它们在不同的程序集中.您可以通过打印m.GetType().AssemblyQualifiedName来看到,其中将包括程序集名称.
标签:anonymous,types,binary,c 来源: https://codeday.me/bug/20191028/1950643.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。