是否可以在Class上添加覆盖所有空字符串属性的自定义属性?像这样:
[DefaultValueForEmptyString(Text="N/A")]
public class PersonsDTO
{
public string Name { get; set; }
public string Lastname { get; set; }
public string Address { get; set; }
}
public class DefaultValueForEmptyString
{
public static void MapProperties(object Properties, string text)
{
foreach (var property in Properties)
{
if(string.IsNullOrEmpty(property))
{
property = text // "N/A in this case
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
为了解决以前的类似问题,我实现了扩展来处理此问题:
public static string ValueOrDefault(this string value)
{
return string.IsNullOrWhiteSpace(value) ? "N/A" : value;
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以在所有字符串属性上使用它:
var person = new PersonsDTO();
//Prints N/A
Console.WriteLine(person.Name.ValueOrDefault());
Run Code Online (Sandbox Code Playgroud)
这并不是很令人印象深刻,但工作已经完成。