risc-v中文社区

 找回密码
 立即注册
查看: 774|回复: 0

[原创] c#对某个没有源代码的类进行功能扩展

[复制链接]

347

主题

564

帖子

2237

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
2237
发表于 2022-7-22 15:32:33 | 显示全部楼层 |阅读模式
目的很简单,有时候,我们需要对一个类进行功能扩展,但要么是别人的代码,自己没有源码,此时下面的4步做法就可以达到这个要法语:
    public static class ExtStringClass //1:必须是静态类
    {
        public static string extStringAdd(this string stringName) //2:第一个参数必须以this开头,并且后面紧接着是要扩展的类,如果不需要参数,则不用添加新的参数列表的
        {
            return stringName + "extStringAdd";
        }
        public static string extStringAdd(this string stringName,string arg) //3:如果需要新的参数,则增加参数列表即可。
        {
            return stringName + arg;
        }
        public static int extGetInt(this string inst)
        {
            try
            {
                int v;
                if (int.TryParse(inst, out v))
                    return v;
                Console.WriteLine("xxx");
            }
            finally
            {
                Console.WriteLine("finally");
            }
            return 0;
        }
    }

4:最终调用的时候,需要用要扩展的类的实例调用扩展方法。
string str = "123;
Console.WriteLine(str.extGetInt());
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则



Archiver|手机版|小黑屋|risc-v中文社区

GMT+8, 2024-4-26 06:25 , Processed in 0.016554 second(s), 17 queries .

risc-v中文社区论坛 官方网站

Copyright © 2018-2021, risc-v open source

快速回复 返回顶部 返回列表