2013-04-09 123 views
2

如何將對象數組轉換爲自定義類數組?

public class ABSInfo 
    { 
     public decimal CodeCoveragePercentage { get; set; } 
     public TestInfo TestInformation { get; set; }  

    } 

而且我有一個對象數組說 「SourceType中」

public object[] SourceType { get; set; } 

我想對象數組(SoiurceType)到ABSInfo []轉換。

我想作爲

ABSInfo[] absInfo = Array.ConvertAll(SourceType, x => (ABSInfo)x); 

但錯誤

無法轉換類型 'WindowsFormsApplication1.TestInfo' 的對象鍵入 'WindowsFormsApplication1.ABSInfo'。

怎麼辦轉換?

編輯:

public class TestInfo 
    { 
     public int RunID { get; set; } 
     public TestRunStatus Status { get; set; } 
     public string Description { get; set; } 
     public int TotalTestCases { get; set; } 
     public int TotalTestCasesPassed { get; set; } 
     public int TotalTestCasesFailed { get; set; } 
     public int TotalTestCasesInconclusive { get; set; } 
     public string ReportTo { get; set; } 
     public string Modules { get; set; } 
     public string CodeStream { get; set; } 
     public int RetryCount { get; set; } 
     public bool IsCodeCoverageRequired { get; set; } 
     public FrameWorkVersion FrameworkVersion { get; set; } 
     public string TimeTaken { get; set; } 
     public int ProcessID { get; set; } 
     public int GroupID { get; set; } 
     public string GroupName { get; set; } 
    } 
+0

什麼是'TestInfo'? – 2013-04-09 12:36:51

+2

你的'ABSInfo'數組中似乎有'TestInfo'? – 2013-04-09 12:37:03

+0

這是另一個班級..看到更新 – 2013-04-09 12:37:25

回答

0

通過使它從TestInfo繼承糾正你ABSInfo類:

public class ABSInfo : TestInfo 
{ 
    public decimal CodeCoveragePercentage { get; set; } 
} 

這將解決轉換問題,還可以直接訪問一個ABSInfo類實例TestInfo性能。

4

你可以使用LINQ;

ABSInfo[] absInfo = SourceType.Cast<ABSInfo>().ToArray(); 

或者

ABSInfo[] absInfo = SourceType.OfType<ABSInfo>().ToArray(); 

第一個會想盡源數組元素鑄造ABSInfo並返回InvalidCastException時,這是不可能的,至少一個元素。

第二個將放於返回的數組僅這些要素,可以澆鑄成ABSInfo對象。

0

你有對象的數組。你不能所有object轉換爲ABSInfo,除非所有的對象都是(更多派生類或)的ABSInfo實例。

所以要麼把空的陣列

ABSInfo[] absInfo = Array.ConvertAll(SourceType, x => x as ABSInfo); 

或不添加東西比ABSInfo別的SourceType

0

這似乎是您的數組包含類型TestInfo的對象。
所以你需要爲你的數組中的每個TestInfo建立一個對象ABSInfo。

在LINQ:

var absInfo = SourceType.Select(s => new ABSInfo() 
          { 
           TestInformation = (TestInfo)s 
          , CodeCoveragePercentage = whatever 
          }).ToArray()