[英]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.