[英]How can a value type implement an interface type?
在C#語言規范v5.0的1.3節中,它說:
接口類型的內容可以是空引用,對實現該接口類型的類類型實例的引用,或者對實現該接口類型的值類型的盒裝值的引用
這三個陳述中有兩個沒有問題。 然而,最后一個讓我困惑。 接口類型如何保存實現該接口類型的值類型的盒裝值? 我認為值類型無法實現接口類型? 或者是說盒裝值實現了接口類型? 如果是這種情況,盒裝值如何實現接口類型?
我在理解所有這些方面遇到了麻煩。
值類型( struct
) 可以實現接口。 它不能繼承另一個struct
,但可以實現接口。
結構可以實現接口,但它們不能從另一個結構繼承。 因此,不能將struct成員聲明為protected。
所以,當你有一個實現IInterface
的struct
,你會做以下事情:
var value = new MyStruct();
var valueAsInterface = (IInterface)value;
valueAsInterface
包含對實現該接口類型的值類型的盒裝值的引用 。
沒有任何東西可以說值類型無法實現接口。
以下代碼完全合法:
interface ITest
{
void DoSomething();
}
struct MyTest : ITest
{
public void DoSomething()
{
// do something
}
}
這是一個例子:
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.