Chapter 13 - Dynamic type and DLR

The content and code of this article is referenced from book Pro C#5.0 and the .NET 4.5 Framework by Apress. The intention of the writing is to review the konwledge and gain better understanding of the .net framework. 

 

1. The role of C# dynamic keyword

We learned implicit varaiable in early chapters, and once the initial assignment has been made, you have a strong typed variable, any attemp to assign an imcompatible value will result in a compiler error.

    static void ImplicitVariable()
        {
            var a = new List<int> ();
            a.Add (90);

            a = "hello"; //compiler error
        }

With the release of .net 4.0, the C# language introduced a keyword named dynamic. From a high level, you can consider the dynamic keyword a specialized form of System.Object, any value can be assigned to a dynamic data type.

What makes a dynamic variable much different from a variable declared implicitly or via a System.Object referent is that it is not strongly typed. Dynamic variable can be assigned with any initial value, and can be reassigned to any new value during its lifetime.

        static void ChangeDynamicData()
        {
            dynamic t = "hello";

            t = false;

            t = new List<int> ();

        }

1.1 Calling member on dynamic data

To invoke methods on dynamic variable, just apply the dot operator and specify a public member. However, the validity of the members you specify will not be checked by the compiler.

        static void InvokeMemberOnDynamicData()
        {
            dynamic data = "hello";
            Console.WriteLine (data.ToUpper ());

            Console.WriteLine (data.toupper ()); //compile file, will have runtime error
        }

1.2 The role of Microsoft.CSharp.dll 

When you create a new visual studio C# project, you will automatically have a reference set to an assembly Microsoft.CSharp.Dll. The most common class, RuntimeBinderException, represents an error that will be thrown if you attempt to invoke a member on a dynamic data, which does not exist.

        static void InvokeMemberOnDynamicData()
        {
            dynamic data = "hello";
            try
            {
                Console.WriteLine (data.ToUpper ());
                Console.WriteLine (data.toupper ());
            }
            catch(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) {
                Console.WriteLine (ex.Message);
            }
        }

1.3 The scope of dynamic keyword

The var keyword can never be used as a return value, a parameter, or a member of a class/structure. This is not the case with dynamic keyword.

    class dynamicClass
    {
        private static dynamic dField;

        public dynamic Property {get;set;}

        public dynamic method(){
            return 1;
        }
    }

1.4 Limitations of the dynamic keyword

While a great many things can be defined using the dynamic keyword, there are some limitations reagarding its usage. The dynamic data item can not make use of lambda expression or C# anonymous methods when calling a methods.  In addition, it has very limited use within LINQ to objects and other LINQ technologies.

1.5 Practise use of the dynamic keyword

In a few circumstances, the dynamic keyword can radically reduce the amount of code you need to write. Specifically, if you are building .net applications that make heavy use of late binding. As well, if you are building a .net application that needs to communicate with legacy COM library.

The use of dynamic keyword is a trade-off between brevity of code, and type safety.

2. The role of Dynamic Language Runtime (DLR)

With the release .net 4.0, the Common Language Runtime (CLR) was supplemented with a complementary runtime environment named the Dynamic Language Runtime (DLR). In a nutshell, a dynamic runtime allows a dynamic language the ability to discover types completely at runtime with no compile-time checks.

2.1 The role of expression trees

The DLR makes use of expression trees to capture the meaning of a dynamic call in neutral terms.

2.2 The role of System.Dynamic namespace

The system.Core.dll assembly includes a namespace named System.Dynamic. You will only make use of the namespace if you want to build a custom runtime builder. 

2.3 Dynamic Runtime lookup of expression trees

If the dynamic data type is pointing in memory to a COM object, the expression tree is sent to a low-level COM interface named IDispatch.

If the dynamic data is not pointing to a COM object, the expression tree may be passed to an object implementing the IDynamicObject interface. This interface is used behind the scenes to allow language such as IronRuby, to take expression tree and map it to ruby specifies.

If the dynamic data is pointing to a normal C# object, the expression tree is dispatched to C# runtime binder.

After the expression tree has been processed by a given binder, the dynamic data will be resolved to the real in-memory data type.

2.4 Late bind calls using dynamic types

//normal procedures of late binding using reflection
        static void LateBinding(Assembly asm)
        {
            try{
                Type car = asm.GetType("CarLibrary.Car");

                object myCar = Activator.CreateInstance(car);

                MethodInfo method = car.GetMethod("Print");

                method.Invoke(myCar, null);
            }
            catch(Exception ex) {
                Console.WriteLine (ex.Message);
            }
        }
        //using dynamic
        static void LateBinding(Assembly asm)
        {
            try{
                Type car = asm.GetType("CarLibrary.Car");

                dynamic myCar = Activator.CreateInstance(car);
                myCar.Print();
            }
            catch(Exception ex) {
                Console.WriteLine (ex.Message);
            }
        }

By declaring the myCar using dynamic, the heavy lifting of reflection is done using DRL.

时间: 2024-12-08 22:29:38

Chapter 13 - Dynamic type and DLR的相关文章

Chapter 20 Dynamic Type

1. The Dynamic Type system is centered around text styles. When a font is requested for a given text style, the system will use the user’s preferred text size in association with the text style to return an appropriately configured font. Below shows

Working with the Dynamic Type in C#

Working with the Dynamic Type in C# https://www.red-gate.com/simple-talk/dotnet/c-programming/working-with-the-dynamic-type-in-c/?utm_source=simpletalkdotnet&utm_medium=pubemail&utm_content=20181127-slota1&utm_term=simpletalkmain by Camilo Rey

《linux 内核完全剖析》chapter 13 内存管理 (不含swap.c)

内存管理(memory.c 和swap.s 部分) "倒着看" 先看memory management,很明显,前面各种阻力,都是因为涉及内存管理.不先看这个,我估计前面看了也是白看 我估算着理论打基础砸了差不多一个星期的时间在memory management上面了...感觉很有收获,是时候用实践(code)印证理论了! <modern operating system>讲内存管理那一章 http://blog.csdn.net/cinmyheart/article/de

iOS Programming Dynamic Type 1

iOS Programming Dynamic Type 1? Dynamic Type is a technology introduced in iOS 7 that helps realize this goal by providing specifically designed text styles that are optimized for legibility. Dynamic Type 是从iOS7引入的技术来帮助实现这个目标通过提供专门设计的text styles 为了优化

Big Nerd iOS Programming 第20章 Dynamic Type 动态类型

Dynamic Type 动态类型 1.比如字体.使用动态的用户自定义的系统字体. -(void)updateFonts    {        UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];        self.nameLabel.font = font;        self.dataLabel.font = font;    } 2.注册,获取修改通知    当用户修改了字体或者系统设置,会

可变cell,自适应cell,理解iOS 8中的Self Sizing Cells和Dynamic Type

在iOS 8中,苹果引入了UITableView的一项新功能--Self Sizing Cells,对于不少开发者来说这是新SDK中一项非常有用的新功能.在iOS 8之前,如果想在表视图中展示可变高度的动态内容时,你需要手动计算行高,而Self Sizing Cells为展示动态内容提供了一个解决方案.以下是你使用Self Sizing Cells时需要注意的事项: 1.为原型单元格定义Auto Layout约束 2.指定表视图的estimatedRowHeight 3.将表视图的rowHeig

理解iOS 8中的Self Sizing Cells和Dynamic Type

本文转载至 http://www.cocoachina.com/ios/20140922/9717.html iOS开发Dynamic TypeSelf Sizing 在iOS 8中,苹果引入了UITableView的一项新功能--Self Sizing Cells,对于不少开发者来说这是新SDK中一项非常有用的新功能.在iOS 8之前,如果想在表视图中展示可变高度的动态内容时,你需要手动计算行高,而Self Sizing Cells为展示动态内容提供了一个解决方案.以下是你使用Self Siz

零元学Expression Blend 4 - Chapter 13 用实例了解布局容器系列-「Pathlistbox」I

原文:零元学Expression Blend 4 - Chapter 13 用实例了解布局容器系列-「Pathlistbox」I 本系列将教大家以实做案例认识Blend 4 的布局容器,此章介绍的布局容器是Blend 4 里的-「Pathlistbox」 ? 本系列将教大家以实做案例认识Blend 4 的布局容器,此章介绍的布局容器是Blend 4 里的-「Pathlistbox」 ? 就是要让不会的新手都看的懂! ? <先来了解Pathlistbox的基本功能> 01 开启一个新专案後,在主

Cpp Chapter 13: Class Inheritance Part1

class inheritance lets you derive new classes from old ones, inheriting its properties of the old class, called the base class With inheritance, you can: 1 add functionality to existing classes 2 add the data a class represents 3 modify how a class m