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

标签 c# inheritance exchangewebservices

我正在使用 Microsoft Exchange Web 服务 (EWS) 托管 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);
            }
        }

    }
}

最佳答案

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

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

如果你真的想要,你可以定义一个隐式或显式转换。通常不鼓励这样做,因为它会引起混淆,因此在执行此操作之前请先阅读显式和隐式转换。我不会告诉你它是怎么做到的:P

关于c# - 函数返回类型 A,使其成为类型 B(继承自 A),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10819949/

相关文章:

postgresql - Postgres : Performance and correctness of inheritance-foreign-key workaround

c# - 将父类(super class)转换为特定的派生类型

c# - 网址中的破折号(映射到操作)

c# - 采用接口(interface)+抽象类的继承设计。好的做法?

Javascript 函数没有从 typescript 中调用

c#-4.0 - 如何使用 folderid 属性获取 Exchange 邮箱地址?

c# - ICalRecurrenceId 的值是否会因重复 session 的每个实例而改变

c# - EWS - 确定电子邮件是回复还是已转发

c# - 通过 HTTP Post 发送 XML 到 IP :Port

c# - 如何对忽略文章 ("the"、 "a"等的 SQLite 查询进行排序)?