遍历字符串c#类型的对象属性

时间:2020-09-02 16:11:01

标签: 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;
        }
    }
 
 ...........
 ...........
}

1 个答案:

答案 0 :(得分:1)

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