2011-12-08 30 views
3

我有一個struct,它實現了一些interface。這工作正常,直到我有一個struct實現的數組,並嘗試隱式地將該數組轉換爲另一個interface類型的數組。 (請參見下面的代碼示例)將接口數組轉換爲數組時,無效的隱式轉換

using System.Collections.Generic; 

namespace MainNS 
{ 
    public interface IStructInterface 
    { 
     string Name { get; } 
    } 

    public struct StructImplementation : IStructInterface 
    { 
     public string Name 
     { 
      get { return "Test"; } 
     } 
    } 

    public class MainClass 
    { 
     public static void Main() 
     { 
      StructImplementation[] structCollection = new StructImplementation[1] 
      { 
       new StructImplementation() 
      }; 

      // Perform an implicit cast 
      IEnumerable<IStructInterface> castCollection = structCollection; // Invalid implicit cast 
     } 
    } 
} 

當編譯上面的代碼中,我得到的錯誤:

error CS0029: Cannot implicitly convert type 'MainNS.StructImplementation[]' to 'MainNS.IStructInterface[]'

如果我改變StructImplementationclass我沒有問題,所以我假設是什麼我試圖做的是無效的;或者我正在失明並失去一些明顯的東西。

任何意見或解釋這將不勝感激。

編輯

如果任何人有這個問題,使用不同的方法不太理想(如在我的情況的情況下),我用LINQ方法Cast<T>()工作圍繞我的問題。所以在上面的例子中,我會使用類似執行轉換:

IEnumerable<IStructInterface> castCollection = structCollection.Cast<IStructInterface>(); 

有MSDN上關於Variance in Generic Types一個很好的文章,我發現非常有用的。

+1

重複http://stackoverflow.com/questions/5825276/ienumerableimyinterface-implicitly-from-class-but-not-from-struct-why – hatchet

+0

你回答了你自己的問題。錯誤解釋了這個錯誤,你所要做的不是有效的C#代碼,解決方案是使用一個類。 –

+0

@Ramhound我以爲我做了一些在C#中無效的東西 - 我正在尋找更多的解釋或某種方向來解釋,就像我現在發現的那樣。 –

回答

2

數組差異ony允許引用保留大小寫,因此僅適用於類。它基本上是將原始數據視爲對不同類型的參考。這對於結構來說是不可能的。

1

結構不支持您在此處使用的協變,因爲它們是值類型而不是引用類型。有關更多信息,請參閱here