C#4.0 Dynamic

前言:dynamic类型,是 C#4.0版本添加的功能,为了补充C#只拥有静态方法、静态变量的缺点。能够增加代码的灵活性。在编译时不检查错误,在运行时检查。

一、官网定义Reference types - C# Reference | Microsoft Learn

dynamic同object、string一样属于C#的内置引用类型。

The object type is an alias for System.Object in .NET. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from System.Object.(任何类型,直接或者间接的继承Object)。因此dynamic也继承于object。

以下几个例子来探索dynamic的功能:

1. 可以替代泛型使用

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;public class DynamicInEditor:EditorWindow
{[MenuItem("Tools/DynamicTest")]public static void Open() {DynamicWord dw = new DynamicWord();Debug.Log(dw.Work(100, 1).GetType());                                   //System.Int32Debug.Log(dw.Work("100", "1").GetType());                               //System.StringDebug.Log(dw.Work(100, "1").GetType());                                 //System.StringDebug.Log(dw.Work("100", 1).GetType());                                 //System.StringDebug.Log(dw.Work(100, 1));                                             //101Debug.Log(dw.Work("100", "1"));                                         //1001Debug.Log(dw.Work(100, "1"));                                           //1001Debug.Log(dw.Work("100", 1));                                           //1001}private void OnGUI(){}
}public class DynamicWord 
{public dynamic Work(dynamic x,dynamic y) {dynamic result = x + y;return result;}
}

2. Dynamic与Var的区别

        从定义看,Dynamic是C# 定义的引用类型,var Declaration statements - C# reference | Microsoft Learn是一个声明关键字,专门声明一些隐式类型的局部变量(Implicitly typed local variables)。

二、在Unity中编写Dynamic程序报错error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'。原因是:

Playe Setting设置

 unity默认使用了.Net Standard2.1框架,阉割了一部分.NetFrameWork的功能

 


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部