我有一個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[]'
如果我改變StructImplementation
到class
我沒有問題,所以我假設是什麼我試圖做的是無效的;或者我正在失明並失去一些明顯的東西。
任何意見或解釋這將不勝感激。
編輯
如果任何人有這個問題,使用不同的方法不太理想(如在我的情況的情況下),我用LINQ方法Cast<T>()
工作圍繞我的問題。所以在上面的例子中,我會使用類似執行轉換:
IEnumerable<IStructInterface> castCollection = structCollection.Cast<IStructInterface>();
有MSDN上關於Variance in Generic Types一個很好的文章,我發現非常有用的。
重複http://stackoverflow.com/questions/5825276/ienumerableimyinterface-implicitly-from-class-but-not-from-struct-why – hatchet
你回答了你自己的問題。錯誤解釋了這個錯誤,你所要做的不是有效的C#代碼,解決方案是使用一個類。 –
@Ramhound我以爲我做了一些在C#中無效的東西 - 我正在尋找更多的解釋或某種方向來解釋,就像我現在發現的那樣。 –