.NET擴展方法使用實例詳解
擴展方法有幾個必要前提:
- 擴展方法所在的類必須是靜態(tài)類
- 擴展方法本身必須是靜態(tài)方法
- 擴展方法參數(shù)中,對類型的擴展參數(shù)前必須加this關(guān)鍵字
擴展基本數(shù)據(jù)類型
針對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;
}
}
}客戶端調(diào)用。
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);
}
}
}
擴展接口
有這樣的一個產(chǎn)品模型。
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}接口提供獲取產(chǎn)品集合的方法。
public interface IProductService
{
IEnumerable<Product> GetProducts();
}接口有2個實現(xiàn)類。
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 = "空調(diào)"}
};
}
}針對接口擴展方法。
public static class ProductServiceExtension
{
public static IEnumerable<Product> GetProductsById(this IProductService productService, int id)
{
return productService.GetProducts().Where(p => p.Id == id);
}
}客戶端調(diào)用。
class Program
{
static void Main(string[] args)
{
IProductService productService = new FoodProducts();
Console.WriteLine("食物類別下總數(shù)量是;{0}", productService.GetProducts().Count());
try
{
Console.WriteLine("找到的產(chǎn)品名稱是:{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";
}
}
}客戶端調(diào)用。
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~";
}
}
}現(xiàn)在要擴展這個私有嵌套類,為其添加一個轉(zhuǎn)換成大寫的方法,通過反射來完成。
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);
//通過反射創(chuàng)建父類私有嵌套類的實例
var c = Activator.CreateInstance(privateClass);
//通過反射獲取父類私有嵌套類的方法
//var callMethod = privateClass.GetMethod("MessageFromChild");
Console.WriteLine(c.ToUpperCaseChildMessage());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
asp.net core利用AccessControlHelper實現(xiàn)控制訪問權(quán)限
這篇文章主要給大家介紹了關(guān)于asp.net core利用AccessControlHelper實現(xiàn)控制訪問權(quán)限的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者使用asp.net core具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2019-10-10
使用updatepanel局部刷新實現(xiàn)注冊時對用戶名的檢測示例
這篇文章主要介紹了使用updatepanel局部刷新實現(xiàn)注冊時對用戶名的檢測示例,需要的朋友可以參考下2014-03-03
ASP.NET?Core中使用Redis實現(xiàn)緩存
本文詳細講解了ASP.NET?Core中使用Redis實現(xiàn)緩存的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03
asp.net DataTable導出Excel自定義列名的方法
本文分享了asp.net DataTable導出Excel 自定義列名的具體實現(xiàn)方法,步驟清晰,代碼詳細,需要的朋友可以參考借鑒,下面就跟小編一起來看看吧2016-12-12
Asp.net 通用萬級數(shù)據(jù)分頁代碼[修正下載地址]
在萬級數(shù)據(jù)量下的分頁代碼2008-10-10
Asp.net回調(diào)技術(shù)Callback學習筆記
這篇文章主要記錄了Asp.net回調(diào)技術(shù)Callback的一些知識,感興趣的朋友可以參考下2014-08-08
ASP.NET MVC5網(wǎng)站開發(fā)文章管理架構(gòu)(七)
繼上一篇把member的用戶部分完成,現(xiàn)在開始做文章管理部分。文章部分根據(jù)涉及顯示現(xiàn)實文章列表,發(fā)布文章,修改和刪除文章等功能。最終的實現(xiàn)目標是使用權(quán)限來控制用戶是否能進行相應操作,管理員權(quán)限的會顯示全部文章列表和我的文章列表,普通用戶只顯示我的文章列表2015-09-09

