(从here重复)
首先 - 请注意,您可以添加构造函数(和其他代码)添加到WCF类 - 您只需要在部分类中完成(并保留生成的代码)。
听起来像类型的列表中的项目需要更改 - 所以我们不能只是施放。反射是一种选择,但速度很慢。由于使用的是3.5,我们也许可以写一个Expression
这样做对我们更有效地沿着... these lines,但使用第二类太:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
static class Program
{
class Foo
{
public int Value { get; set; }
public override string ToString()
{
return Value.ToString();
}
}
class Bar : Foo {}
static void Main()
{
List<Foo> foos = new List<Foo>();
for (int i = 0; i < 10; i++) foos.Add(new Foo { Value = i });
List<Bar> bars = foos.ConvertAll<Bar>(Clone<Foo, Bar>);
}
public static TTo Clone<TFrom, TTo>(this TFrom obj) where TTo : TFrom, new()
{
return ObjectExtCache<TFrom, TTo>.Convert(obj);
}
static class ObjectExtCache<TFrom, TTo> where TTo : TFrom, new()
{
private static readonly Func<TFrom, TTo> converter;
static ObjectExtCache()
{
ParameterExpression param = Expression.Parameter(typeof(TFrom), "in");
var bindings = from prop in typeof(TFrom).GetProperties()
where prop.CanRead && prop.CanWrite
select (MemberBinding)Expression.Bind(prop,
Expression.Property(param, prop));
converter = Expression.Lambda<Func<TFrom, TTo>>(
Expression.MemberInit(
Expression.New(typeof(TTo)), bindings), param).Compile();
}
public static TTo Convert(TFrom obj)
{
return converter(obj);
}
}
}
不WCF在代理代码中生成_partial_类? – 2009-02-05 16:12:23
乍一看,你并没有说DerivedClass只是在基础之上的功能扩展,或者实际上必须是代码示例所建议的不同的数据结构。恕我直言,在第二种情况下,“转换”是没有意义的。 – 2009-02-05 16:17:56