【问题标题】:How to remove special characters from a class object C#如何从类对象中删除特殊字符C#
【发布时间】:2020-09-05 08:58:44
【问题描述】:

我有一个具有近 200 个属性的类对象,需要从属性值中删除特殊字符。从类对象的属性中删除特殊字符的有效方法是什么。类中的属性在接收来自服务的输入时包含特殊字符。如果类中的属性较少,则可以为每个属性完成。除了使用反射之外,还有其他方法可以从属性中删除特殊字符吗?

【问题讨论】:

  • 您是指属性值中的“特殊”字符还是属性名称中的 C# 保留字符?
  • 属性(getter 和 setter)值。例如,属性 FirstName 必须仅包含字母,但错误地包含服务(用户发送 - 它是拼写错误且用户端没有验证)特殊字符。特殊字符在很多地方都有。所以需要删除类中所有属性的特殊字符。如果数字属性较少,则可以调用正则表达式方法并删除每个属性的特殊字符。现在该类有 200 多个属性。

标签: c# class reflection properties attributes


【解决方案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]");

Fiddle

【讨论】:

    【解决方案2】:

    第一种方法是将类的属性参数化,然后将正则表达式传递给每个属性。

    与库一起使用 System.Text.RegularExpressions;

    然后在这里做一个你之前无法测试的正则表达式:https://regexr.com

    然后创建一个Regex类的对象。之后将您的正则表达式传递给字符串。

    您可以在 Microsoft Doc 中查看示例:https://docs.microsoft.com/es-es/dotnet/api/system.text.regularexpressions.regex?view=netcore-3.1

    【讨论】:

      猜你喜欢
      • 2019-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多