使用扩展方法(this 扩展类型)

本文详细介绍了C#中扩展方法的使用方式,通过具体的代码示例展示了如何为现有类添加新功能,而无需修改其源代码。重点讲解了扩展方法的语法、作用域及其实现细节。

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


namespace ConsoleApp_UseExtendWays
{
class Program
{
static void Main(string[] args)
{
Student s = new Student();
Console.WriteLine(s.GetSexString());
Console.WriteLine(s.GetAge());
Console.ReadKey();
}
}
public static class StudentExtension
{
public static string GetSexString(this Student argStudent)//扩展方法 this 扩展类型
{
return argStudent.GetSex() == true ? "男" : "女";
}

public static int GetAge(this Student ss)
{
return ss.Age;
}
}
public class Student
{
public bool GetSex()
{
return false;
}

public int Age = 12;
}

//public static class StudentConverter
//{
// public static string GetSexString(Student argStudent)
// {
// return argStudent.GetSex() == true ? "男" : "女";
// }
//}
}
posted on 2014-03-18 22:43  v.e.n.u.s 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/jx270/p/3608938.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值