允许

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

最佳答案

由于您的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() };

10-04 22:24