简体   繁体   English

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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