首页 > 编程语言 >《c#高级编程》第4章C#4.0中的更改(六)——动态绑定

《c#高级编程》第4章C#4.0中的更改(六)——动态绑定

时间:2023-04-25 09:04:08浏览次数:34  
标签:4.0 Person c# Age C# int person 动态 Name

一、概念

下面是一些代码示例,说明C#动态绑定的上述特点:

1. 延迟确定类型

```
dynamic obj = GetDynamicObject(); // 获取动态对象
obj.DoSomething(); // 在运行时才能确定DoSomething方法是否存在及其参数类型和返回值类型
```

2. 动态调用成员

```
dynamic obj = GetDynamicObject(); // 获取动态对象
var result = obj.MethodName(arg1, arg2); // 在运行时动态调用MethodName方法,并传递arg1和arg2作为参数
```

3. 动态转换类型

```
dynamic obj = GetDynamicObject(); // 获取动态对象
string str = (string)obj; // 在运行时将动态对象转换为字符串类型
string[] arr = (string[])obj; // 在运行时将动态对象转换为字符串数组类型
```

4. 动态创建对象

```
dynamic obj = Activator.CreateInstance(type); // 在运行时动态创建指定类型的实例
obj.CallWebService(param1, param2); // 在运行时动态调用Web服务,并传递param1和param2作为参数
```

需要注意的是,这些示例只是简单地说明了C#动态绑定的特点,并不能代表所有的应用场景和使用方式。在实际开发中,需要根据具体需求和情况选择合适的技术和方案。

二、实例

C#动态绑定是指在运行时为对象添加成员或调用方法,而不需要在编译时预先声明这些成员或方法。这种机制可以让程序更加灵活,适应不同场景的需求。

以下是C#动态绑定的一些经典应用场景:

  1. 通过反射访问类型成员
using System;
using System.Reflection;

// 定义一个Person类
class Person {
    public string Name {get; set;}
    public int Age {get; set;}
}

class Program {
    static void Main(string[] args) {
        // 获取Person类型
        Type personType = typeof(Person);

        // 获取Name属性信息
        PropertyInfo nameProperty = personType.GetProperty("Name");

        // 创建一个Person实例
        var person = new Person();

        // 设置Name属性值
        nameProperty.SetValue(person, "Tom");

        // 获取Age属性信息
        PropertyInfo ageProperty = personType.GetProperty("Age");

        // 设置Age属性值
        ageProperty.SetValue(person, 20);

        // 输出Person实例信息
        Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
        // 输出结果:Name: Tom, Age: 20
    }
}
  1. 动态创建对象
using System;

// 定义一个Person类
class Person {
    public string Name {get; set;}
    public int Age {get; set;}
}

class Program {
    static void Main(string[] args) {
        // 动态创建Person实例
        var person = Activator.CreateInstance<Person>();

        // 设置Name和Age属性值
        person.Name = "Tom";
        person.Age = 20;

        // 输出Person实例信息
        Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
        // 输出结果:Name: Tom, Age: 20
    }
}
  1. 动态调用方法
using System;
using System.Reflection;

// 定义一个Calculator类
class Calculator {
    public int Add(int a, int b) {
        return a + b;
    }

    public int Substract(int a, int b) {
        return a - b;
    }
}

class Program {
    static void Main(string[] args) {
        // 创建一个Calculator实例
        var calculator = new Calculator();

        // 获取Add方法信息
        MethodInfo addMethod = calculator.GetType().GetMethod("Add");

        // 调用Add方法并输出结果
        int result = (int)addMethod.Invoke(calculator, new object[]{3, 5});
        Console.WriteLine(result); // 输出结果:8

        // 获取Substract方法信息
        MethodInfo substractMethod = calculator.GetType().GetMethod("Substract");

        // 调用Substract方法并输出结果
        result = (int)substractMethod.Invoke(calculator, new object[]{6, 4});
        Console.WriteLine(result); // 输出结果:2
    }
}

 

标签:4.0,Person,c#,Age,C#,int,person,动态,Name
From: https://www.cnblogs.com/DinAction/p/17351519.html

相关文章

  • 《c#高级编程》第4章C#4.0中的更改(七)——命名参数和可选参数
    一、概念C#中的命名参数和可选参数是两种函数参数的特殊形式,它们可以提高代码的可读性和灵活性。命名参数命名参数允许我们在调用函数时指定参数名称,从而不必按照函数定义时的参数顺序进行传参。这样做可以使代码更加易读易懂,同时也可以提高代码的灵活性,因为我们可以只传递某些......
  • windows+centos+ubuntu多系统环境,ubuntu启动修复
    故障现象:       在windows中调整分区后,ubuntu系统无法启动,centos启动进入保护模式解决过程一、双硬盘,centos硬盘EFI分区还在,ubuntu硬盘EFI分区消失,发现一个300的分区但是不是efi分区,查看分区无数据重建EFI分区fdisk/dev/nvme0n1p1  d删除原有分区n新建分区 ......
  • K8s 集群 etcd节点故障解决方案
    1环境说明k8s版本:v1.20etcd节点(192.168.0.12)故障: 报错详情: 4月2422:47:13k8s-node2etcd[9543]:{"level":"warn","ts":"2023-04-24T22:47:13.571+0800","caller":"etcdserver/server.go:2065","msg":......
  • 解决npm install各种报错的6种方案 Error: Command failed: cmd.exe autoreconf -ivf
    报错示例:Error:Commandfailed:C:\Windows\system32\cmd.exe/s/c"autoreconf-ivf"gifsiclepre-buildtestfailedPSG:\code_all\my_webpack_webgl2021-5-17-dev_01\three151-demo>npminstallnpmnoticeBeginningOctober4,2021,allconnect......
  • CodeStar2023年春第6周周赛普及进阶组
    T1:最长倍数序列本题难度中等,先把\(a\)从小到大排序。dp[i]表示以\(a_i\)结尾的倍数序列。转移如下:只有\(a_i\),对应长度\(dp[i]=1\)上一个数是\(a_j(1\leqslantj\leqslanti-1)\),若\(a_j\)是\(a_i\)的约数,就更新\(dp[i]=\max(dp[i],dp[j]+1)\)最终答......
  • 自定义Python版本ESL库访问FreeSWITCH
    环境:CentOS7.6_x64Python版本:3.9.12FreeSWITCH版本:1.10.9一、背景描述ESL库是FreeSWITCH对外提供的接口,使用起来很方便,但该库是基于C语言实现的,Python使用该库的话需要使用源码进行编译。如果使用系统自带的Python版本进行编译,过程会比较流畅,就不描述了。这里记录下使用自定义......
  • Reset an Internet Connection (Flush DNS)
    https://support.pearson.com/getsupport/s/article/Reset-an-Internet-Connection-Flush-DNSWindows10.8and8.1Navigatetothedesktop.(FromHome,taporclicktheDesktoptile).Right-clicktheStartbutton(theWindowslogointhelower-left).ChooseComma......
  • Codeforces Round #459 (Div. 2) D. MADMAX DAG&&博弈
    Asweallknow,Maxisthebestvideogameplayeramongherfriends.Herfriendsweresojealousofhers,thattheycreatedanactualgamejusttoprovethatshe’snotthebestatgames.Thegameisplayedonadirectedacyclicgraph(aDAG)withnvertic......
  • 2016 ACM/ICPC Asia Regional Qingdao Online E
    Rock-paper-scissorsisazero-sumhandgameusuallyplayedbetweentwopeople,inwhicheachplayersimultaneouslyformsoneofthreeshapeswithanoutstretchedhand.Theseshapesare“rock”,“paper”,and“scissors”.Thegamehasonlythreepossible......
  • 2017 ACM-ICPC, Universidad Nacional de Colombia Programming Contest D
    AlexhastwomagicmachinesAandB.MachineAwillgiveyou2x + 1coinsifyouinsertxcoinsinit,machineBwillgiveyou2x + 2.Alexhasnocoinsandwantstogetexactlyncoinsinordertobuyanewunicorn,buthecan’tfigureouthowtodoi......