2014-01-25 45 views
8

在C#語言規範5.0版,在1.3節中,這樣說:值類型如何實現接口類型?

一個接口類型可以具有作爲其內容一個空引用,對實現該一個類類型的 實例的引用接口類型或 參考對實現該 接口類型

我沒有問題與三分之二那些語句的值類型的裝箱值。然而,最後一個讓我困惑。接口類型如何保存實現該接口類型的值類型的裝箱值?我認爲值類型不能實現接口類型?或者是說盒裝值實現了接口類型?如果是這種情況,盒裝值如何實現接口類型?

我有一個麻煩理解這一切。

+0

這是此 – alamin

回答

11

數值類型(struct可以執行接口。它不能繼承另一個struct,但可以實現接口。

struct (C# Reference)

結構可以實現一個接口,但它們不能從另一個結構繼承。出於這個原因,struct成員不能被聲明爲protected。

所以,當你有一個struct它實現IInterface和你以下幾點:

var value = new MyStruct(); 
var valueAsInterface = (IInterface)value; 

valueAsInterface包含參考對實現該接口類型值類型的裝箱值。

+0

一個很好的問題+1你能不能說'IInterface valueAsInterface = value'? –

+0

是的,你可以。不會有任何區別(除非在結構體中覆蓋cast操作符)。 – MarcinJuraszek

+1

爲什麼你需要設置一個實現接口類型的值類型?所有這些行話都讓我頭暈目眩。 –

5

沒有什麼說價值類型不能實現接口。

下面的代碼是完全合法:

interface ITest 
{ 
    void DoSomething(); 
} 

struct MyTest : ITest 
{ 
    public void DoSomething() 
    { 
     // do something 
    } 
} 
1

下面是一個例子:

interface DisplayMsg 
{ 
    void ShowMsg(); 
} 
/// <summary> 
/// Interface implemented by Struct 
/// </summary> 
struct StructDisplayMsg : DisplayMsg 
{ 

    public void ShowMsg() 
    { 
     Console.WriteLine("Inside struct Showmsg:"); 
    } 
} 
/// <summary> 
/// Interface implemented by Class 
/// </summary> 
class ObjectDisplayMsg:DisplayMsg 
{ 
    public int Integer { get; set; } 

    public void ShowMsg() 
    { 
     Console.WriteLine("Inside Object ShowMsg:{0}", Integer); 
    } 
    /// <summary> 
    /// Implicit operator for boxing value type to object 
    /// </summary> 
    /// <param name="value"></param> 
    /// <returns></returns> 
    public static implicit operator ObjectDisplayMsg(int value) 
    { 
     ObjectDisplayMsg classObject = new ObjectDisplayMsg(); 
     classObject.Integer = value; 
     return classObject; 
    } 
} 

private void CheckConcepts() 
{ 
    StructDisplayMsg localDisplay = new StructDisplayMsg(); 
    localDisplay.ShowMsg(); 

    int localInteger = 10; 
    /* Boxing of the integer type to Object */ 
    ObjectDisplayMsg intobject = (ObjectDisplayMsg)localInteger; 
    intobject.ShowMsg(); 
    Console.ReadKey(); 
} 
相關問題