我有一个第三方库返回一个对象数组的对象数组,我可以填充到一个对象[]:
object[] arr = myLib.GetData(...);
Run Code Online (Sandbox Code Playgroud)
结果数组由object []条目组成,因此您可以将返回值视为某种记录集,其中外部数组表示行,而内部数组包含可能未填充某些字段的字段值(锯齿状数组) .要访问各个字段,我必须像:
int i = (int) ((object[])arr[row])[col];//access a field containing an int
Run Code Online (Sandbox Code Playgroud)
现在因为我很懒,我想要访问这样的元素:
int i = (int) arr[row][col];
Run Code Online (Sandbox Code Playgroud)
为此,我使用以下Linq查询:
object[] result = myLib.GetData(...);
object[][] arr = result.Select(o => (object[])o ).ToArray();
Run Code Online (Sandbox Code Playgroud)
我尝试使用简单的强制转换,object[][] arr = (object[][])result;但失败并出现运行时错误.
现在,我的问题:
编辑:
谢谢大家的快速回答.
@James:我喜欢你在新课程中结束罪魁祸首的答案,但缺点是我在接受源数组时总是要做Linq包装,而索引器需要row和col值int i = (int) arr[row, col]; (我需要得到一个完整的行也很喜欢object[] row = arr[row];,抱歉没有发布在开头).
@Sergiu Mindras:像James一样,我认为扩展方法有点危险,因为它适用于所有object[]变量.
@Nair:我为我的实现选择了你的答案,因为它不需要使用Linq包装器,我可以int i = (int) arr[row][col];使用object[] row = arr[row];
@quetzalcoatl和@Abe Heidebrecht 使用或整行访问两个单独的字段:感谢提示Cast<>(). …
为了简化使用特定类型的字典,我从通用Dictionary <>派生了一个类来处理从公共基类派生的各种元素:
//my base class holding a value
public abstract class A{ public int aValue; }
//derived classes that actually are stuffed into the dictionary
public class B : A {...}
public class C : A {...}
//wrapper class for dictionary
public class MyDict : Dictionary<string, A>;
//my class using the dictionary
public class MyClass {
public MyDict dict = new MyDict();//use an instance of MyDict
public MyClass() { ... //fill dict with instances of B and C }
//function …Run Code Online (Sandbox Code Playgroud)