在您原始问题的评论中,您说:
“进行强制转换的原因是对象图始于应用程序A,对象图被序列化并传递到应用程序B或应用程序C。应用程序B和C扩展了对象图以满足自己的目的。应用程序A不知道应用程序B或C或应用程序B和C对对象图所做的任何操作。应用程序B和C是非常不同的应用程序。”
然而,在问题中,您提出了一个好的解决方案:
“不修改客户端或地址对象”
强制转换无法为对象添加功能。对象必须已经具备这些功能。
因此,听起来您不想更改类型,只想在解决方案的某些区域内为这些类型添加额外的设施。
因此,您需要
扩展方法。
您将保留
Client
和
Address
类型,但通过扩展方法添加其他设施:
public static class MyExtensions
{
public static void SendLetter(this Address address, string messageBody)
{
}
}
这样可以让你编写:
someClient.Addresses[0].SendLetter("Dear Sir, K THX BAI")
您可能需要在每个 Address
对象中存储额外的数据。可能最方便的现成解决方案是让 Address
派生自 DependencyObject,这样可以使用 DependencyProperty 实例作为键来存储额外的数据:
public static class MyExtensionsWithData
{
public static readonly DependencyProperty PhoneProperty =
RegisterAttached("PhoneNumber",
typeof(string),
typeof(MyExtensionsWithData));
public static void SetPhoneNumber(this Address address, string phone)
{
address.SetValue(PhoneProperty, phone);
}
public static string GetPhoneNumber(this Address address)
{
return (string)address.GetValue(PhoneProperty);
}
}
这样,您可以有效地向现有对象添加新属性,并可以像这样使用它们:
// set
someClient.Addresses[0].SetPhoneNumber("5550945793847");
// get
string phoneNum = someClient.Addresses[0].GetPhoneNumber();