gpt4 book ai didi

c# - 如何通过自定义Attribute获取和修改属性值?

转载 作者:可可西里 更新时间:2023-11-01 07:45:32 24 4
gpt4 key购买 nike

我想创建一个可用于以下属性的自定义属性:

[TrimInputString]
public string FirstName { get; set; }

这将在功能上等同于

private string _firstName
public string FirstName {
set {
_firstName = value.Trim();
}
get {
return _firstName;
}
}

所以基本上每次设置属性值都会被修剪。

如何从属性中解析值、修改该值然后使用新值设置属性?

[AttributeUsage(AttributeTargets.Property)]
public class TrimInputAttribute : Attribute {

public TrimInputAttribute() {
//not sure how to get and modify the property here
}

}

最佳答案

我正在这样做,不是很令人信服的方式,但它的工作

演示课

public class User
{

[TitleCase]
public string FirstName { get; set; }

[TitleCase]
public string LastName { get; set; }

[UpperCase]
public string Salutation { get; set; }

[LowerCase]
public string Email { get; set; }

}

属性为小写,其他类似写法

public class LowerCaseAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
//try to modify text
try
{
validationContext
.ObjectType
.GetProperty(validationContext.MemberName)
.SetValue(validationContext.ObjectInstance, value.ToString().ToLower(), null);
}
catch (System.Exception)
{
}

//return null to make sure this attribute never say iam invalid
return null;
}
}

虽然不是很优雅,因为它实际实现了 Validation 属性,但它有效

关于c# - 如何通过自定义Attribute获取和修改属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2864343/

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