具有2个兼容类的属性

时间:2017-12-29 17:16:55

标签: c#

权限

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覆盖属性,因为它们是兼容的?

2 个答案:

答案 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();