c# – 验证接口属性

我做了一个接口IRequest:

public interface IRequest
{
    [DataMember(IsRequired = true)]
    string EndUserIp { get; set; }

    [DataMember(IsRequired = true)]
    string TokenId { get; set; }

    [DataMember(IsRequired = true)]
    string ClientId { get; set; }

    [DataMember(IsRequired = true)]
    int TokenAgencyId { get; set; }

    [DataMember(IsRequired = true)]
    int TokenMemberId { get; set; }
}

我已经在多个班级实现了这个;现在我需要验证所有属性:

 public static bool ValidateCommon(IRequest request)
    {
        if (string.IsNullOrWhiteSpace(request.ClientId))
            throw new BusinessServiceException(ErrorType.InvalidRequest, "ClientId can not be null or Empty");
        if (string.IsNullOrWhiteSpace(request.TokenId))
            throw new BusinessServiceException(ErrorType.InValidSession, "TokenID should not be Null or Empty");
        if (!IsValidTokenId(request.TokenId))
            throw new BusinessServiceException(ErrorType.InValidSession, "TokenID is not in correct Format");
        if (string.IsNullOrWhiteSpace(request.EndUserIp))
            throw new BusinessServiceException(ErrorType.InValidIpAddress, "IP Address should not be Null or Empty");
        if (!IsValidIp(request.EndUserIp))
            throw new BusinessServiceException(ErrorType.InValidIpAddress, "IP Address is not in correct Format");
        if (request.TokenAgencyId < 0)
            throw new BusinessServiceException(ErrorType.InvalidRequest, "TokenAgencyId should be positive Integer");
        if (request.TokenMemberId <= 0)
            throw new BusinessServiceException(ErrorType.InvalidRequest, "TokenMemberId should be positive Integer");
        return true;
    }

但我不想一次又一次地写这个方法.那么做同样的方法是什么?

最佳答案 使用名为Validate的函数创建一个名为IRequestValidator的接口,该函数采用IRequest.需要验证IRequest时,实现接口并实例化/注入组件.

这样您就可以在一个地方获得验证系统,并在以后轻松交换它(如果您注入组件;如果不是,请使用工厂模式以避免在代码中对组件的新调用进行硬编码).

public interface IRequestValidator {
    bool Validate(IRequest req);
}

// at first you have one way of validating elements

public class AllWelcomeValidator: IRequestValidator {
    public bool Validate(IRequest req) {return true; // no validation atm }
}

// later...

public class NowWeGotRulesValidator: IRequestValidator {
    public bool Validate(IRequest req) {
        if (string.IsNullOrWhiteSpace(request.ClientId))
            throw new BusinessServiceException(ErrorType.InvalidRequest, "ClientId can not be null or Empty");
        // etc...
    }
}
点赞