2013-04-09 140 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() 
相关问题