C#自定義轉(zhuǎn)換器的實現(xiàn)
一般我們想到轉(zhuǎn)換器是否都是Int 轉(zhuǎn)換成 double類型,Double 類型轉(zhuǎn)換成Int類型?;蛘吒鼜?fù)雜一點的是Object 轉(zhuǎn)換成 File 等引用類型。這種都涉及到了類型之間的轉(zhuǎn)換,其實C#已經(jīng)幫我們實現(xiàn)了。
如何實現(xiàn)一個更復(fù)雜的;兩個類型之間 的轉(zhuǎn)換呢?這里需要我們自定義類型轉(zhuǎn)換方法 。
1.自定義轉(zhuǎn)換語法
這里列舉一個例子,我們這里有Student類 和 Employ類 我想實現(xiàn)這兩種數(shù)據(jù)類型的轉(zhuǎn)換。

這里有兩個方法,第一個方法將Studnet 類型轉(zhuǎn)換成Employee類型。
用Static implicit 修飾 是代表隱式轉(zhuǎn)換 返回的是Employee 實例就是 轉(zhuǎn)換成Employee類型。
用Static explicit 修飾代碼的是顯示轉(zhuǎn)換,返回的是Student 實例就是轉(zhuǎn)換成Student類型。
2.使用
這里我把之前的單例模式再復(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)換的類型 返回該類型對象 沒有方法名,這里的方法名就是轉(zhuǎn)換的類型。
Static explicit 表示顯式轉(zhuǎn)換 修飾同上。
到此這篇關(guān)于C#自定義轉(zhuǎn)換器的實現(xiàn)的文章就介紹到這了,更多相關(guān)C#自定義轉(zhuǎn)換器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#線程 BeginInvoke和EndInvoke使用方法
本文開始C#線程系列講座之一,即BeginInvoke和EndInvoke的使用方法,需要的朋友可以參考下2013-05-05

