網站首頁 編程語言 正文
擴展方法有幾個必要前提:
- 擴展方法所在的類必須是靜態類
- 擴展方法本身必須是靜態方法
- 擴展方法參數中,對類型的擴展參數前必須加this關鍵字
擴展基本數據類型
針對DateTime類型寫一個擴展方法。
public static class CalculateAge
{
public static int Age(this DateTime date, DateTime birthDate)
{
int birthYear = birthDate.Year;
int currentYear = DateTime.Now.Year;
if (birthYear >= currentYear)
{
throw new Exception("請輸入正確的出生日期~~");
}
else
{
return currentYear - birthYear - 1;
}
}
}
客戶端調用。
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("請輸入您的出生年份");
DateTime d = Convert.ToDateTime(Console.ReadLine());
DateTime dateInstance = new DateTime();
int age = dateInstance.Age(d);
Console.WriteLine("您當前的年齡是:{0}", age);
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
擴展接口
有這樣的一個產品模型。
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
接口提供獲取產品集合的方法。
public interface IProductService
{
IEnumerable<Product> GetProducts();
}
接口有2個實現類。
public class FoodProducts : IProductService
{
public IEnumerable<Product> GetProducts()
{
return new List<Product>
{
new Product(){Id = 1, Name = "餅干"},
new Product(){Id = 2, Name = "牛奶"}
};
}
}
public class ElectronicProducts : IProductService
{
public IEnumerable<Product> GetProducts()
{
return new List<Product>
{
new Product(){Id = 3, Name = "電風扇"},
new Product(){Id = 4, Name = "空調"}
};
}
}
針對接口擴展方法。
public static class ProductServiceExtension
{
public static IEnumerable<Product> GetProductsById(this IProductService productService, int id)
{
return productService.GetProducts().Where(p => p.Id == id);
}
}
客戶端調用。
class Program
{
static void Main(string[] args)
{
IProductService productService = new FoodProducts();
Console.WriteLine("食物類別下總數量是;{0}", productService.GetProducts().Count());
try
{
Console.WriteLine("找到的產品名稱是:{0}", (productService.GetProductsById(1).SingleOrDefault()).Name);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}
}
擴展包含私有字段的類 使用反射獲取類的私有字段
擴展一個類的時候,有時候會用到該類的私有字段,我們可以通過反射拿到類的私有字段。
有這樣的一個類,包含私有字段和公共方法。
{
private DateTime _currentTime;
public void SetTime()
{
_currentTime = DateTime.Now;
}
public string GetMsg()
{
if (_currentTime.Hour < 12)
{
return "上午好~~";
}
else
{
return "下午好~~";
}
}
}
我們希望擴展出一個顯示英文信息的問候。
public static class DisplayMessageExtensions
{
public static string GetLocalMsg(this DisplayMessage message, string country)
{
//通過反射拿到私有字段
var privateField = typeof (DisplayMessage).GetField("_currentTime",
BindingFlags.Instance | BindingFlags.NonPublic);
//獲取該私有字段的值
var currentDateTime = (DateTime)privateField.GetValue(message);
if (country == "USA" && currentDateTime.Hour < 12)
{
return "Good Morning";
}
else
{
return "Good Evening";
}
}
}
客戶端調用。
class Program
{
static void Main(string[] args)
{
DisplayMessage displayMessage = new DisplayMessage();
displayMessage.SetTime();
Console.WriteLine("來自中國的問候是:{0}", displayMessage.GetMsg());
Console.WriteLine("美國人怎么問候?");
Console.WriteLine("來自美國的問候是:{0}", displayMessage.GetLocalMsg("USA"));
Console.ReadKey();
}
}
擴展一個類的私有嵌套類 通過反射
當一個類有嵌套私有類的時候,擴展該類的時候,有時候會用到該類的嵌套私有類,我們可以通過反射擴展私有嵌套類。
有這樣的一個ParentClass類,包含一個私有嵌套類ChildClass.
public class ParentClass
{
public string MessageFromParent()
{
return "from parent~~";
}
private class ChildClass
{
public string MessageFromChild()
{
return "from child~";
}
}
}
現在要擴展這個私有嵌套類,為其添加一個轉換成大寫的方法,通過反射來完成。
public static class NestedClassExtension
{
public static string ToUppeerCaseParentMessage(this ParentClass parent)
{
return parent.MessageFromParent().ToUpper();
}
public static string ToUpperCaseChildMessage(this object o)
{
var childUpper = "";
//通過反射獲取父類中的私有嵌套類
var privateClass = typeof (ParentClass).GetNestedType("ChildClass", BindingFlags.NonPublic);
if (o.GetType() == privateClass)
{
//通過反射獲取嵌套私有類的方法
var callMethod = privateClass.GetMethod("MessageFromChild");
childUpper = (callMethod.Invoke(o, null) as string).ToUpper();
}
return childUpper;
}
}
客戶端,首先通過反射獲取私有嵌套類的type類型,然后運用私有嵌套類的擴展方法。
try
{
ParentClass p = new ParentClass();
//通過反射獲取父類私有嵌套類
var privateClass = typeof (ParentClass).GetNestedType("ChildClass", BindingFlags.NonPublic);
//通過反射創建父類私有嵌套類的實例
var c = Activator.CreateInstance(privateClass);
//通過反射獲取父類私有嵌套類的方法
//var callMethod = privateClass.GetMethod("MessageFromChild");
Console.WriteLine(c.ToUpperCaseChildMessage());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
原文鏈接:https://www.cnblogs.com/darrenji/p/3853087.html
相關推薦
- 2023-02-01 Python?AI編程助手AICodeHelper使用示例_python
- 2022-11-18 Android?使用壓縮紋理的方案_Android
- 2022-09-22 右值引用(C++11)
- 2022-05-02 C語言遞歸實現歸并排序詳解_C 語言
- 2022-06-06 typescript類型別名、限制值的大小
- 2024-07-15 Spring Boot多環境指定yml或者properties
- 2022-07-03 pandas創建series的三種方法小結_python
- 2022-12-27 詳解C#中線程傳參,返回值和多線程沖突問題的解決_C#教程
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支