[英]iterate through object properties of type string c#
我有一个对象“人”,里面有一长串名称、城市、年龄等属性。我的目标是当我收到这个对象时,迭代抛出字符串属性,并检查字符串是否有任何特殊字符。 我唯一的问题是迭代部分。 到目前为止我得到了什么(迭代是错误的......)
public ActionResult Index(Person person)
{
var haveSpecialCharacters = false;
foreach (var property in typeof(Person).GetProperties())
{
if (property.PropertyType == typeof(string) && !Validate(property))
{
haveSpecialCharacters = true;
break;
}
}
...........
...........
}
bool IsPersonInvalid(Person person)
{
bool HasSpecialCharacter(string value)
{
// Replace with something more useful.
return value?.Contains("$") == true;
}
return typeof(Person)
// Get all the public Person properties
.GetProperties()
// Only the ones of type string.
.Where(x => x.PropertyType == typeof(string))
// Get the values of all the properties
.Select(x => x.GetValue(person) as string)
// Check any have special chars
.Any(HasSpecialCharacter);
}
var person1 = new Person
{
FirstName = "Bob$Bob",
LastName = "Fred"
};
Console.WriteLine(IsPersonInvalid(person1)); // True
var person2 = new Person
{
FirstName = "Bob",
LastName = "Fred"
};
Console.WriteLine(IsPersonInvalid(person2)); // False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.