考虑这个People
类:
public class People
{
public virtual string Name { get; set; }
public virtual ushort Age { get; set; }
}
我有一些第三方实现可以获取人员数据,但有一些变化。例如,我有一个能够检索数据的方法StrangePeople
:
public class StrangePeople
{
public string Name { get; set; }
public DateTime BirthDate { get; set; }
}
...
StrangePeople someone = GetData<StrangePeople>();
由于类和变体的数量,我试图找到一种方法来生成People
可以转换数据的运行时子类,以便我可以将其转换回People
以后。换句话说,用最小的努力生成一个像这样的子类:
public class StrangePeopleTranslator : People
{
private ushort? _mAge = null;
public override ushort Age
{
get
{
if (_mAge == null)
{
DateTime today = DateTime.Today;
int age = today.Year - BirthDate.Year;
if (BirthDate > today.AddYears(-age)) age--;
_mAge = age;
}
return _mAge.GetValueOrDefault();
}
set
{
_mAge = value;
}
}
public DateTime BirthDate { get; set; }
}
...
People someoneElse = (People)GetData<StrangePeopleTranslator>();
也许运行时子类有点矫枉过正......我不知道。