如何转换两个自定义对象数组

巨应打字员 2010-10-20 06:20:02
例如我有两个结构体

struct A
{
public int Field1;
public int Field2;
}

struct B
{
public int Field1;
public int Field2;
}


通过重载操作符号,可以得到
B b=new B();
A a=(A)b;

但是却不能
A[] arr=(A[])barr;


我又想通过一个方法去转换
   
/// <summary>
///把原始数组转换为目标数组
/// </summary>
/// <typeparam name="T">目标类型</typeparam>
/// <param name="source">原始数组</param>
/// <returns>成功返回转换后的数组</returns>
public static T[] Transfer<T>(object source) where T : new()
{
if (!(source is Array))
return null;

IList enumerAbleSource = (IList)source;
List<T> l = new List<T>();
try
{
foreach (var item in enumerAbleSource)
{
l.Add((T)(item));
}
}
catch
{
return null;
}

return l.ToArray();
}


但是这个方法是不行的,
跪求大侠们一个方法,可以转换转换两个不同结构体的数组,不要foreach挨个转换,因为用的地方多,看起来很重复
...全文
88 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
sprc_lcl 2010-10-21
  • 打赏
  • 举报
回复
exp:

string[] str = new string[] { "1", "2" };
int[] ints;
ints = Array.ConvertAll(str, new Converter<string, int>(delegate(string s)
{
return Convert.ToInt32(s);
}));
MessageBox.Show(ints.Length.ToString());
巨应打字员 2010-10-21
  • 打赏
  • 举报
回复
- -用 linq 的 select 还是可以比较简单的完成


config.MainVideoEncOpt = wrapConfig.stMainVideoEncOpt.Select(arg => (VideoEncOpt)arg).ToArray();
巨应打字员 2010-10-21
  • 打赏
  • 举报
回复
顶起啊....是我没表达清楚,还是怎么的?
xuld 2010-10-20
  • 打赏
  • 举报
回复
在 .net 4以前时无法完成的


A[] a = new A[];
B[] b = new b[];
foreach(A f in a)
b <- f

110,530

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧