2012-05-30 144 views
1

我正在使用Microsoft Exchange Web服務(EWS)託管API 1.2從使用C3的Exchange郵箱訪問數據。返回的對象的某些屬性很難訪問,因爲它們是自定義屬性。函數返回類型A,使其類型B(從A繼承)

爲了簡化訪問這些屬性,我寫了一個名爲Contact2的類,它擴展了EWS給我的Contact類。

當調用一個返回Contact對象的函數時,如何將其升級到Contact2?

這裏是Contact2 I類寫道:

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); 
      } 
     } 

    } 
} 

回答

3

您需要定義Contact2接受Contact對象明確的靜態方法或構造函數。即

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

如果你確實想要,你可以定義一個隱式或顯式轉換。這通常是令人沮喪的,因爲它可能會導致混淆,因此在執行此操作之前,請先閱讀顯式和隱式轉換。我不會告訴你它是如何完成的:P

1

即使其他類繼承了Contact,也不能神奇地將現有的Contact實例轉換爲另一個類。

您需要修改創建Contact創建Contact2代替,或寫自己的功能,創建一個Contact2一個包裝了現有Contact實例的代碼。

+0

如何包裝現有的聯繫人實例?我發現的所有示例代碼只是將Contact對象分配給Contact2對象的屬性。有沒有辦法來包裝它,以便我不必通過Contact2對象的屬性調用方法和屬性? – longneck

+0

@longneck:您可以將屬性和方法添加到'Contact2',以傳遞給'Contact'中的屬性和方法。 – SLaks

相關問題