简体   繁体   中英

iterate through object properties of type string c#

i have an object "Person" with a long list of proprieties Name, City, Age, etc. My goal is when i receive this object, to iterate throw the proprieties that are strings, and check if the strings have any special characters. My only problem here is the iteration part. what i got so far (the iteration is wrong...)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM