c# - 遍历字符串类型的对象属性 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;
}
}
...........
...........
}
解决方案
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
推荐阅读
- typescript - Inversify 实例未正确注入
- javascript - 如何在 Vue cli 中导入使用其他本地文件中的函数的 JavaScript 文件而不会出现未定义的错误?
- html - 响应式表格,在桌面上工作,但在移动设备上不完全相同
- php - 我可以在表格中填写数组吗
- python - 使用 Python Selenium 的 csvWriter 不会遍历 0 到 j - 它只接受最后一次点击而不是每次点击
- node.js - 带有端口的AWS公共IP不适用于nodejs
- xamarin - 由于链接器问题,Xamarin iOS 绑定库 (Swift) 构建错误
- python - 如何让客户端套接字继续在 python 中侦听服务器?
- python - Kivy 和 Python 如何在同一视频的两个 Videoplayer 上播放视频 定位到另一个
- html - 当我更改父元素的高度时图像变形