我有一个典型的网站管理员部分,管理员可以添加许多不同的实体。作为开发人员,我必须修剪它们(以防止输入类似于'状态名称的实体'。我这样做,即在Validate方法IValidatableObject接口中:
public class AddProjectViewModel : ProjectFormBaseViewModel, IValidatableObject
{
public int? ParentProjectID { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
ProjectName = ProjectName.Trim();
DescriptionText = DescriptionText.Trim();
当然,我可以在项目添加到DB或其他任何方法的方法中执行此操作。 但是如果我有10个表单,并且每个表单都有2-3个字符串属性,那么这个代码有点&#34;直接&#34;。也许任何人都可以推荐其他更多&#34;美丽&#34;修剪所有字符串参数的方法?即通过属性的属性或其他东西?
答案 0 :(得分:5)
为什么不使用反射?
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教程将为您提供帮助。
答案 1 :(得分:0)
你可以修剪ViewModel本身的属性吗?
public class MyModel
{
private string _prop;
public string Prop
{
get
{
return !string.IsNullOrEmpty(_prop) ? _prop.Trim() : this._prop;
}
set
{
this._prop = value.Trim();
}
}
}