接口不匹配属性访问器

时间:2018-01-07 22:57:55

标签: c# syntax accessor

我有一个简单的接口,我想用不同的Accessors实现

public interface IValidatorByState : IValidator
{
    AuthorizedDbContext Context { get; set; }
}

我试图在具有Public,或受保护的Get和内部集的类上实现此功能;

编辑此类是向用户公开的,他们应该只能检索上下文。

public class ValidatorByState<TEntity> : AbstractValidator<TEntity>, IValidatorByState
{
    public AuthorizedDbContext Context { get; internal set;}
}

无论采用哪种方式实施此操作我都会收到错误

尝试:

public AuthorizedDbContext Context { get; internal set;}
  

ValidatorByState.Context不公开

protected AuthorizedDbContext Context { get; internal set;}
  

ValidatorByState.Context.set Accessor必须比property更严格,

AuthorizedDbContext _context;
public AuthorizedDbContext IValidatorByState.Context => this._context;
public AuthorizedDbContext IValidatorByState.Context {
    set { this._context = value; }
}

为此,我在说明

时收到错误
  

显式实现缺少Accessor

如何使用内部集合获得公共get方法?

2 个答案:

答案 0 :(得分:3)

我会创建一个只读的公共接口和带有setter方法/属性的内部接口。必须明确实现内部接口:

public interface IValidatorByStateReadOnly 
{
    AuthorizedDbContext Context { get; }
}  

internal interface IValidatorByState : IValidatorByStateReadOnly
{
    new AuthorizedDbContext Context { get; set; }
}

public class ValidatorByState<TEntity> : IValidatorByState
{
    private AuthorizedDbContext _context;

    public AuthorizedDbContext Context => _context;

    AuthorizedDbContext IValidatorByState.Context 
    {
        get => _context;
        set => _context = value; 
    }
}

答案 1 :(得分:2)

接口成员必须是公开的。

如何:

public interface IValidatorByStateReader
{
    AuthorizedDbContext Context { get; }
}

internal interface IValidatorByStateWriter
{
    AuthorizedDbContext Context { set; }
}

public class ValidatorByState<TEntity> : IValidatorByStateReader, IValidatorByStateWriter
{
    private AuthorizedDbContext _context;
    AuthorizedDbContext IValidatorByStateReader.Context => this._context;
    AuthorizedDbContext IValidatorByStateWriter.Context { set => this._context = value; }
}