函数返回类型 A,使其成为类型 B(继承自 A)

本文关键字:继承 类型 返回类型 函数 | 更新日期: 2023-09-27 18:35:42

我正在使用Microsoft Exchange Web Services (EWS) Managed API 1.2 使用 C3 访问 Exchange 邮箱中的数据。返回的对象的某些属性很难访问,因为它们是自定义属性。

为了简化对这些属性的访问,我编写了一个名为 Contact2 的类(作为一个例子),该类扩展了 EWS 提供给我的 Contact 类。

调用返回 Contact 对象的函数时,如何将其"升级"为 Contact2?

这是我写的 Contact2 类:

namespace ExchangeContacts
{
    class Contact2 : Microsoft.Exchange.WebServices.Data.Contact
    {
        public ExchangeService ex = new ExchangeService();
        public Dictionary<string, ExtendedPropertyDefinition> propDefs = new Dictionary<string, ExtendedPropertyDefinition>();
        public PropertySet myPropSet = new PropertySet();
        public Contact2(ExchangeService service)
            : base(service)
        {
            propDefs.Add("MarketingGuid", new ExtendedPropertyDefinition(new Guid("3694fe54-daf0-49bf-9e37-734cfb8521e1"), "MarketingGuid", MapiPropertyType.String));
            myPropSet = new PropertySet(BasePropertySet.FirstClassProperties) { propDefs["MarketingGuid"] };
            ex = service;
        }
        new public void Load()
        {
            base.Load(myPropSet);
        }
        new public void Load(PropertySet propertySet)
        {
            propertySet.Add(propDefs["MarketingGuid"]);
            base.Load(propertySet);
        }
        public string MarketingGuid
        {
            get
            {
                string g;
                if (TryGetProperty(propDefs["MarketingGuid"], out g))
                    return g;
                else
                    return "";
            }
            set
            {
                SetExtendedProperty(propDefs["MarketingGuid"], value);
            }
        }
    }
}

函数返回类型 A,使其成为类型 B(继承自 A)

您需要在 Contact2 中定义一个显式静态方法或构造函数,该构造函数接受 Contact 对象。

public static Contact2 FromContact(Contact cnt)
{
    return new Contact2(cnt.x, cnt.y, ...)
}

如果确实需要,可以定义隐式或显式转换。通常不建议这样做,因为它可能会导致混淆,因此在执行此操作之前,请阅读显式和隐式转换。我不会告诉你它是怎么做到的:P

您无法神奇地将现有的Contact实例转换为另一个类,即使该其他类继承了Contact

您需要修改创建Contact的代码以改为创建Contact2,或者编写自己的函数来创建包装现有Contact实例的Contact2

你可以为Contact添加一个运算符重载,那么你就不需要静态方法,或者至少必须将它们公开。

这有点难以完全正确...请参阅如何重写基类的 == 运算符,以便调用重写