首页 > 解决方案 > 遍历字符串类型的对象属性 c#

问题描述

我有一个对象“Person”,其中包含一长串属性名称、城市、年龄等。我的目标是当我收到这个对象时,迭代抛出作为字符串的属性,并检查字符串是否有任何特殊字符。我这里唯一的问题是迭代部分。到目前为止我得到了什么(迭代是错误的......)

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;
        }
    }
 
 ...........
 ...........
}

标签: c#

解决方案


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

推荐阅读