2010-03-09 71 views
0

我需要一個包裝類來公開實體類ProfileEntity的一些屬性。無法執行轉換

我試着從這個實體派生出來,然後創建返回特定實體屬性的屬性,但它說我不能從ProfileEntity投到ProfileEntityWrapper

當我嘗試將返回一個'ProfileEntity'的方法的返回值放入包裝中時,我得到上述錯誤。

如何創建這樣一個可澆注的包裝類?

class ProfileEntityWrapper : ProfileEntity 
{ 
    public string Name 
    { 
     get 
     { 
      return this.ProfileEntityName; 
     } 
    } 
} 

public class Someclass 
{ 
    public ProfileEntity SomeMethod() 
    { 
    return ProfileEntity; // example of method returning this object 
    } 
} 

public class SomeOtherlClass 
{ 
    SomeClass sc = new SomeClass(); 

    public void DoSomething() 
    { 
    ProfileEntityWrapper ew = (ProfileEntityWrapper)sc.SomeMethod(); // Cannot do this cast!!! 
    } 
} 
+0

你能表現出一定的代碼? class a:b {}可以讓你做(a)b;你不需要做(b)a;因爲a已經是b @ – 2010-03-09 10:43:53

+0

@Rune FS:添加了一些示例代碼 – 2010-03-09 10:49:43

+0

,因爲SomeMethod返回ProfileEntity的實例,但不是ProfileEntityWrapper的實例。 – garik 2010-03-09 11:12:51

回答

1

不能投ProfileEntity的一個目的是ProfileEntityWrapper。

var entity = new ProfileEntity(); // this object is only of type ProfileEntity 
var wrapper = new ProfileEntityWrapper(); // this object can be used as both ProfileEntityWrapper and ProfileEntity 

你可能想在的someMethod(返回ProfileEntityWrapper):

public class Someclass 
{ 
    public ProfileEntity SomeMethod() 
    { 
     return new ProfileEntityWrapper(); // it's legal to return a ProfileEntity 
    } 
} 
+0

但我想要另一種方式,有沒有解決這個問題的方法? – 2010-03-09 11:30:35

+1

在我看來,包裝不應該繼承包裝類型。試着讓包裝通過構造函數接收一個ProfileEntity,並在成員變量privateEventity _innerEntity中記住它;在Name屬性中,您可以返回_innerEntity.ProfileEntityName; – bjornhol 2010-03-09 11:45:20

1

不,那是不可能的。

爲了完成這個問題你也許可以試試這個:

public class ProfileEntity 
{ 
    public string ProfileEntityName { get; set; } 
} 

public class ProfileEntityWrapper 
{ 
    public ProfileEntityWrapper(ProfileEntity entity) 
    { 
     Entity = entity; 
    } 

    public ProfileEntity Entity { get; private set; } 

    public string Name 
    { 
     get 
     { 
      return Entity.ProfileEntityName; 
     } 
    } 
} 

public class SomeClass 
{ 
    public ProfileEntity SomeMethod() 
    { 
     // example of method returning this object 
     ProfileEntity temp = new ProfileEntity(); 
     return temp; 
    } 
} 

public class SomeOtherClass 
{ 
    SomeClass sc = new SomeClass(); 

    public void DoSomething() 
    { 
     //Create a new Wrapper for an existing Entity 
     ProfileEntityWrapper ew = new ProfileEntityWrapper(sc.SomeMethod()); 
    } 
} 
0

如果你被允許編輯ProfileEntity類,或者如果ProfileEntity類是生成的部分類,你可以添加一個接口,而不是使用包裝。你不需要使用接口進行任何類型的轉換。示例:

​​

IProfile實例將僅提供對Name屬性的訪問。

0

這是多態性方面沒有正確的代碼。 如果我們將着名的多態性示例,當有基本的Shape類和擴展Shape類的Circle,Polygon和Rectangle類時,您的代碼將嘗試將某些形狀轉換爲圓形,並且您知道這是無效的投射操作。 因此,爲了使你必須確保SomeClass.SomeMethod()將返回ProfileEntityWrapper的實例或鑄造之前進行類型檢查,這樣此代碼的工作:

ProfileEntity temp = sc.SomeMethod(); 
if(temp is ProfileEntityWrapper) 
    ProfileEntityWrapper ew = (ProfileEntityWrapper) temp;