权限
public enum PermissionType
{
Read = 0,
Write = 1
}
public class Permission
{
public virtual PermissionType? Type { get; set; }
}
public class PermissionCreate : Permission
{
[Required]
[Range(0, 1)]
public override PermissionType? Type { get; set; }
}
分类
public class Category
{
public virtual int? Id { get; set; }
public virtual string Name { get; set; }
public virtual Permission Permission { get; set; }
}
public class CategoryCreate : Category
{
[Required]
public override string Name { get; set; }
[Required]
public override PermissionCreate Permission { get; set; }
}
行public override PermissionCreate Permission { get; set; }
抛出错误,因为它需要匹配重写的成员类型。有没有办法用Permission和PermissionCreate覆盖属性,因为它们是兼容的?
答案 0 :(得分:3)
由于您的PermissionCreate
课程已来自Permission
:
public class PermissionCreate : Permission
然后您就可以将PermissionCreate
对象分配给Permission
属性。
但是,是的,派生类必须与父类完全匹配。所以,如果你这样做:
public class CategoryCreate : Category
{
[Required]
public override string Name { get; set; }
[Required]
public override Permission Permission { get; set; }
}
然后你可以这样做:
var test = new CategoryCreate { Permission = new PermissionCreate() };
答案 1 :(得分:1)
您无需创建CategoryCreate
课程。而是使用Category
对象创建PermissionCreate
实例:
Category Create = new Category();
Create.Permission = new PermissionCreate();