Trim 所有属性的操作

Trim actions for all properties

我有一个带有管理部分的典型网站,管理员可以在其中添加许多不同的实体。作为开发人员,我必须 trim 每个(以防止输入像“状态名称”这样的实体。我这样做,即在 Validate 方法 IValidatableObject 接口中:

   public class AddProjectViewModel : ProjectFormBaseViewModel, IValidatableObject
    {
        public int? ParentProjectID { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            ProjectName = ProjectName.Trim();
            DescriptionText = DescriptionText.Trim();

当然,我可以在项目添加到数据库或其他任何东西的方法中完成。 但是如果我有10个表单,每个表单有2-3个字符串属性,那么这段代码就有点"straight"了。也许有人可以推荐其他 "beautiful" 方法来 trim 所有字符串参数? IE。通过 属性 或其他属性?

为什么不用反射?

var obj = YourObjectToBeTrimmed();
foreach(var property in obj.GetType().GetProperties().Where(x => x.PropertyType == typeof(string))) {
    property.SetValue(obj, (property.GetValue(obj) as string).Trim());
}

也可以使用反射的属性或其他修改。

编辑。现在,由于 OP 的要求,我修改了我的答案。在下面的代码中,所有由 TrimAttribute 标记的属性都将被修剪。

class Program {
        static void Main(string[] args) {
            // The sample properties.
            var notTrimmedString = "  smth   ";
            var trimmedString = notTrimmedString.Trim();

            // Prepare an object to trim its properties.
            var obj = new A {
                PropertyToBeTrimmed = notTrimmedString,
                PropertyNotToBeTrimmed = notTrimmedString,
            };

            // Trim properties marked by TrimAttribute.
            foreach(var property in obj.GetType().GetProperties().Where(x => 
                x.PropertyType == typeof(string) &&
                x.GetCustomAttributes(typeof(TrimAttribute), true).Any())) {
                property.SetValue(obj, (property.GetValue(obj) as string).Trim());
            }

            // Check.
            Console.WriteLine(obj.PropertyToBeTrimmed == notTrimmedString);
            Console.WriteLine(obj.PropertyNotToBeTrimmed == notTrimmedString);
            Console.WriteLine(obj.PropertyToBeTrimmed == trimmedString);
            Console.WriteLine(obj.PropertyNotToBeTrimmed == trimmedString);
            Console.ReadKey();
        }
    }

    /// <summary>
    /// Sample class.
    /// </summary>
    class A {
        /// <summary>
        /// This property must be marked by TrimAttribute. 
        /// So it will be trimmed.
        /// </summary>
        [Trim]
        public string PropertyToBeTrimmed { get; set; }

        /// <summary>
        /// This property must be not marked by TrimAttribute. 
        /// So it will not be trimmed.
        /// </summary>
        public string PropertyNotToBeTrimmed { get; set; }
    }

    /// <summary>
    /// Custom attribute which means need for trimming.
    /// </summary>
    class TrimAttribute : Attribute { }

如果您不熟悉反射和属性,我想 this 教程会对您有所帮助。

你能trim ViewModel 本身的属性吗?

public class MyModel
{
    private string _prop;

    public string Prop
    {
        get
        {
            return !string.IsNullOrEmpty(_prop) ? _prop.Trim() : this._prop;
        }
        set
        {
            this._prop = value.Trim();
        }
    }
}