C#自定義轉(zhuǎn)換器的實(shí)現(xiàn)
一般我們想到轉(zhuǎn)換器是否都是Int 轉(zhuǎn)換成 double類型,Double 類型轉(zhuǎn)換成Int類型?;蛘吒鼜?fù)雜一點(diǎn)的是Object 轉(zhuǎn)換成 File 等引用類型。這種都涉及到了類型之間的轉(zhuǎn)換,其實(shí)C#已經(jīng)幫我們實(shí)現(xiàn)了。
如何實(shí)現(xiàn)一個(gè)更復(fù)雜的;兩個(gè)類型之間 的轉(zhuǎn)換呢?這里需要我們自定義類型轉(zhuǎn)換方法 。
1.自定義轉(zhuǎn)換語法
這里列舉一個(gè)例子,我們這里有Student類 和 Employ類 我想實(shí)現(xiàn)這兩種數(shù)據(jù)類型的轉(zhuǎn)換。
這里有兩個(gè)方法,第一個(gè)方法將Studnet 類型轉(zhuǎn)換成Employee類型。
用Static implicit 修飾 是代表隱式轉(zhuǎn)換 返回的是Employee 實(shí)例就是 轉(zhuǎn)換成Employee類型。
用Static explicit 修飾代碼的是顯示轉(zhuǎn)換,返回的是Student 實(shí)例就是轉(zhuǎn)換成Student類型。
2.使用
這里我把之前的單例模式再?gòu)?fù)習(xí)一遍。
namespace Study12_自定義數(shù)據(jù)類型轉(zhuǎn)換.Common { public class Singleton<T> where T : class { private static object _object = new object(); private static T _instance; public static T Instance { get { if (_instance == null) { lock (_object) { if (_instance == null) { _instance = Activator.CreateInstance<T>(); } return _instance; } } return _instance; } } } }
public class DataConverter:Singleton<DataConverter> { public Student GetStudent(Employee emp) { return (Student)emp; } public Employee GetEmployee(Student student) { return student; } }
使用
internal class Program { static void Main(string[] args) { Employee employee= DataConverter.Instance.GetEmployee(new Student { Id = 1, Name = "小明" }); employee.DoWork(); Console.WriteLine("Hello, World!"); //throw new NotImplementedException(); } }
輸出
3.總結(jié)
static implicit 表示隱式類型轉(zhuǎn)換 修飾要轉(zhuǎn)換的類型 返回該類型對(duì)象 沒有方法名,這里的方法名就是轉(zhuǎn)換的類型。
Static explicit 表示顯式轉(zhuǎn)換 修飾同上。
到此這篇關(guān)于C#自定義轉(zhuǎn)換器的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)C#自定義轉(zhuǎn)換器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#實(shí)現(xiàn)自定義線程池實(shí)例代碼
這篇文章介紹了C#實(shí)現(xiàn)自定義線程池的實(shí)例代碼,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07C#線程 BeginInvoke和EndInvoke使用方法
本文開始C#線程系列講座之一,即BeginInvoke和EndInvoke的使用方法,需要的朋友可以參考下2013-05-05C#命令模式(Command Pattern)實(shí)例教程
這篇文章主要介紹了C#命令模式(Command Pattern),以實(shí)例的形式講述了命令模式通過一個(gè)指令來控制多個(gè)類的多個(gè)方法,需要的朋友可以參考下2014-09-09