gpt4 book ai didi

c# - 将值传递给自定义属性

转载 作者:行者123 更新时间:2023-11-30 17:28:47 27 4
gpt4 key购买 nike

我想自定义一个属性。说

public class IdExistAttribute : ValidationAttribute
{

protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
string id= value.ToString();
if(ListOfId.Contains(id))
{
return new ValidationResult("Id is already existing");
}

return ValidationResult.Success;
}
}

问题是 ListOfId 是来自服务的,我不能在属性里面消费服务。那么如何从外部传递呢?

我想将属性用作

private string _id;
[IdExist]
public string Id
{
get{return _id;}
set{_id=value;}
}

最佳答案

ValidationContext通过 GetService 提供对已注册依赖项注入(inject)容器的访问。

引用 Andrew Lock :

As you can see, you are provided a ValidationContext as part of the method call. The context object contains a number of properties related to the object currently being validated, and also this handy number:

public object GetService(Type serviceType);

所以你可以像这样使用ValidationContext:

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var service = (IExternalService) validationContext
.GetService(typeof(IExternalService));
// use service
}

关于c# - 将值传递给自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52107193/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com