2010-03-09 28 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;