委托实现的一个“多态”

本文介绍C#中如何使用自定义类和委托来动态实现字符串转换方法。通过定义委托类型并将其作为参数传递给类的方法,可以实现在运行时确定具体执行哪个方法的功能。示例展示了将字符串转换为大写的动态方法实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 委托实例
{
    class MyClass
    {
        public void Change(string[] s, ChangeDelegate changeDelegate)//委托动态实现一个方法
        {
            for (int i = 0; i < s.Length; i++)
            {

                //这边不确定到时候传过来一个什么方法,使用委托动态实现,相当于一个方法的占位符
                s[i] = changeDelegate(s[i]);
            }
        }
    }

    //传方法时传递一个有参数有返回值的方法
    public delegate string ChangeDelegate(string s);
}

主类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 委托实例
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] s = new string[] { "yangdelong", "wanhaigou", "jierke", "goubao" };
            MyClass mc = new MyClass();
            mc.Change(s, ChangeS);
            for (int i = 0; i < s.Length; i++)
            {
                Console.WriteLine(s[i]);
            }
            Console.ReadKey();
        }

        //这就是传过来的具体方法
        static string ChangeS(string s)
        {
           
               return s.ToUpper();     
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值