如何从 class 对象 C# 中删除特殊字符
How to remove special characters from a class object C#
我有一个包含近 200 个属性的 class 对象,需要从 属性 值中删除特殊字符。从 class 对象的属性中删除特殊字符的有效方法是什么。 class 中的属性在接收来自服务的输入时包含特殊字符。如果 class 中的属性较少,则可以对每个 属性 执行此操作。除了使用反射之外,还有其他方法可以从属性中删除特殊字符吗?
第一种方法是参数化 class 的属性,然后将正则表达式传递给每个属性。
使用库 System.Text.RegularExpressions;
然后在这里做一个你之前无法测试的正则表达式:https://regexr.com
然后创建 class 正则表达式的对象。之后将您的正则表达式传递给字符串。
您可以在 Microsoft Doc 中查看示例:https://docs.microsoft.com/es-es/dotnet/api/system.text.regularexpressions.regex?view=netcore-3.1
有 200 个属性(将来可能会更多),最好的选择可能是按照您的建议使用反射并结合正则表达式。
public void CleanupPropertyValues()
{
PropertyInfo[] properties =
typeof(Person).GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (PropertyInfo property in properties)
{
if (property.PropertyType == typeof(string))
{
string currentValue = (string)property.GetValue(this, null);
if (!string.IsNullOrEmpty(currentValue))
{
string newValue = _cleanupRegex.Replace(currentValue, "");
if (newValue != currentValue)
{
property.SetValue(this, newValue);
}
}
}
}
}
private static Regex _cleanupRegex = new Regex("[^A-Za-z]");
我有一个包含近 200 个属性的 class 对象,需要从 属性 值中删除特殊字符。从 class 对象的属性中删除特殊字符的有效方法是什么。 class 中的属性在接收来自服务的输入时包含特殊字符。如果 class 中的属性较少,则可以对每个 属性 执行此操作。除了使用反射之外,还有其他方法可以从属性中删除特殊字符吗?
第一种方法是参数化 class 的属性,然后将正则表达式传递给每个属性。
使用库 System.Text.RegularExpressions;
然后在这里做一个你之前无法测试的正则表达式:https://regexr.com
然后创建 class 正则表达式的对象。之后将您的正则表达式传递给字符串。
您可以在 Microsoft Doc 中查看示例:https://docs.microsoft.com/es-es/dotnet/api/system.text.regularexpressions.regex?view=netcore-3.1
有 200 个属性(将来可能会更多),最好的选择可能是按照您的建议使用反射并结合正则表达式。
public void CleanupPropertyValues()
{
PropertyInfo[] properties =
typeof(Person).GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (PropertyInfo property in properties)
{
if (property.PropertyType == typeof(string))
{
string currentValue = (string)property.GetValue(this, null);
if (!string.IsNullOrEmpty(currentValue))
{
string newValue = _cleanupRegex.Replace(currentValue, "");
if (newValue != currentValue)
{
property.SetValue(this, newValue);
}
}
}
}
}
private static Regex _cleanupRegex = new Regex("[^A-Za-z]");