我需要一个包装类来公开我的实体类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!!!
}
}发布于 2010-03-09 19:10:23
不能将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
}
}发布于 2010-03-09 19:59:17
不,这不可能。
要解决这个问题,你可以试试下面这个:
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());
}
}发布于 2010-03-09 23:23:27
如果允许您编辑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属性的访问。
https://stackoverflow.com/questions/2408353
复制相似问题