一文带你了解 C# DLR 的世界(DLR 探秘)

2020-02-22 21:57:46刘景俊

这里顺便想问下各位,有没有mac下c#反编译的工具。求推荐

所以我们在写重载方法时,是不能以 object 和 dynamic 来区分的。

void DynamicMethod(object o);
void DynamicMethod(dynamic d); // error 编译器无法通过编译:已经存在同名同形参的方法

如果说 dynamic 与 object 一样,那么它与 DLR 又有什么关系呢?

其实微软提供这么一个关键字,我认为是方便提供创建动态类型的快捷方式。而真正于动态类型密切相关的是命名空间System.Dynamic下的类型。主要核心类DynamicObject,ExpandoObject,IDynamicMetaObjectProvider ,关于这三个类我们这节先不谈。

DLR探秘

首先我们来大致了解C#4.0加入的重要功能 DLR,在编译器中处于什么层次结构。

在这里我引用 https://www.codeproject.com/Articles/42997/NET-4-0-FAQ-Part-1-The-DLR 这片文章的一副结构图的意思

动态编程 = CLR + DLR

这足以说明 DLR 在C#中的位置,虽然名字与CLR只有一个字母之差,但是它所处的层次其实是在CLR之上的。我们知道编译器将我们写的代码转换成IL,然后经由CLR转换成本地代码交由CPU执行可执行程序。那么实际上,DLR 是在编译期间和运行期做了大量工作。最后还是会将C#代码转换成CLR静态语言,然后再经由 CLR 将代码转换成本地代码执行(如调用函数等)。

现在我们来简要介绍一下DLR在编译期间做了什么。

到这里就不得不以例子来做说明了,我们就上面的例子稍加改造一下:

// program.cs
dynamic x = "marson shine";
string v = x.Substring(6);
Console.WriteLine(v);

为了节省篇幅,我简化并改写了难看的变量命名以及不必要的注释。生成的代码如下:

 object obj1 = (object) "marson shine";
 staticCallSite1 = staticCallSite1 ?? CallSite<Func<CallSite, object, int, object>>.Create(Binder.InvokeMember(CSharpBinderFlags.None, "Substring", (IEnumerable<Type>) null, typeof (Example), (IEnumerable<CSharpArgumentInfo>) new CSharpArgumentInfo[2]
 {
 CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, (string) null),
 CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.Constant, (string) null)
 }));

 object obj2 = ((Func<CallSite, object, int, object>) staticCallSite1.Target)((CallSite) staticCallSite1, obj1, 6);
 staticCallSite2 = staticCallSite2 ?? CallSite<Action<CallSite, Type, object>>.Create(Binder.InvokeMember(CSharpBinderFlags.ResultDiscarded, "WriteLine", (IEnumerable<Type>) null, typeof (Example), (IEnumerable<CSharpArgumentInfo>) new CSharpArgumentInfo[2]
 {
 CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.IsStaticType, (string) null),
 CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, (string) null)
 }));

 ((Action<CallSite, Type, object>) staticCallSite2.Target)((CallSite) staticCallSite2, typeof (Console), obj2);