我需要一个包装类来公开我的实体类的一些名为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 :(得分: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
}
}
答案 1 :(得分: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());
}
}
答案 2 :(得分:0)
如果允许编辑ProfileEntity类,或者如果ProfileEntity类是生成的分部类,则可以添加接口而不是使用包装器。您也不需要使用接口进行任何转换。例如:
public interface IProfile
{
string Name { get; }
}
public partial class ProfileEntity : IProfile
{
public string Name
{
get
{
return this.ProfileEntityName;
}
}
}
public class SomeClass
{
public ProfileEntity SomeMethod()
{
return ProfileEntity;
}
}
public class SomeOtherClass
{
SomeClass sc = new SomeClass();
public void DoSomething()
{
IProfile ew = sc.SomeMethod();
}
}
IProfile实例仅提供对Name属性的访问。
答案 3 :(得分:0)
这不是来自多态方面的正确代码。 如果我们将采用着名的多态性示例,当有基础Shape类和扩展Shape类的Circle,Polygon和Rectangle类时,您的代码将尝试将某些形状转换为圆形,并且您理解这是无效的转换操作。 因此,要使此代码工作,您必须确保SomeClass.SomeMethod()将返回ProfileEntityWrapper的实例或在转换之前执行类型检查,如下所示:
ProfileEntity temp = sc.SomeMethod();
if(temp is ProfileEntityWrapper)
ProfileEntityWrapper ew = (ProfileEntityWrapper) temp;