我有一个带有管理部分的典型网站,管理员可以在其中添加许多不同的实体。作为开发人员,我必须修剪它们中的每一个(以防止输入像“状态名称”这样的实体。我这样做,即在 Validate 方法 IValidatableObject 接口(interface)中:
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 个字符串属性,那么这段代码就有点“直白”了。也许有人可以推荐其他更“漂亮”的方法来修剪所有字符串参数? IE。通过属性(property)的属性或其他什么?
最佳答案
为什么不用反射?
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如果您不熟悉反射和属性,本教程将为您提供帮助。
关于c# - 修剪所有属性的 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30261076/