[英]Struct in interface again; Why can I use it like class?
為什么我可以使用((I)o).Set(5,5); 它輸出5,5是,o是對象,但我不能((I)s.Set(4,4); //輸出1,1為什么((I)s).Set(4,4)的輸出保持不變,而((I)o).Set(5,5)的輸出卻改變了?
我知道我的代碼隱式地將(引用)轉換為I(引用)。 問題也在代碼注釋中。
interface I
{
void Set(int x, int y);
}
public struct S : I
{
int x, y;
public S(int x, int y)
{
this.x = x;
this.y = y;
}
public void Set(int x, int y)
{
this.x = x;
this.y = y;
}
public override string ToString()
{
return String.Format("{0} {1}", x, y);
}
}
class Program
{
static void Main(string[] args)
{
try
{
S s = new S(1, 1);
Console.WriteLine(s);
object o = s;
((I)o).Set(5, 5);
Console.WriteLine(o); // Why this works like class and outputs 5,5 instead of 1,1?
((I)s).Set(4, 4); // why i can`t change reference. why it outputs 1,1 instead of 4,4
}
catch { }
}
}
當您進行強制轉換(I)s
,通過復制s
創建S
(I)s
另一個實例,並將其放入堆中,因為接口是引用類型。 因此,此時您有兩個S
實例:一個在堆棧中,另一個在堆中。
因此,當您執行((I)s).Set(4, 4);
您正在更改第二個,即堆中的一個。
最后Console.WriteLine(s);
正在打印第一個,即堆棧中的第一個。
要獲得正確的輸出,您必須執行以下操作:
var i = (I)s;
i.Set(4, 4);
Console.WriteLine(i);
因為什么時候
((I)s).Set(4, 4)
被稱為發生了什么事
1)((I)s)將結構轉換為對象(裝箱)
2)Set方法將更改應用於該對象(后來由於沒有引用指向該對象而被垃圾收集器丟棄),但結構保持不變
((I)o)是否將一種引用類型轉換為另一種引用類型,但對象保持不變。
從這里進行了解釋: https : //blogs.msdn.microsoft.com/abhinaba/2005/10/05/c-structs-and-interface/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.