简短说明:
我需要在将一些文本保存到数据库之前对其进行清理。
我们有一个项目,包含我们的MVC应用程序中使用的所有模型。有一个Save(T record)
方法可以将实体保存到数据库中。我被要求做的是在将其保存到数据库之前清理传入对象的类型字符串的每个属性。但是,存在一个问题:如何从传入实体中清理自定义数据类型属性的属性?
详细说明: 假设我有一个类型为Address的类和一个类型为Person的类,它具有Address:
类型的属性 public class Address
{
public string StreetName { get; set; }
public string City { get; set; }
public int StreetNumber { get; set; }
}
public class Person
{
public string PersonName { get; set; }
public Address HomeAddress { get; set; }
}
在我使用此泛型方法检索string类型的属性之前:
public static void SanitizeObject<TEntity>(TEntity record)
{
var props =
record.GetType().GetProperties()
.Where(x => x.CanRead && x.CanWrite)
.Where(x => x.PropertyType == typeof (string));
foreach (var property in props)
{
string value = Convert.ToString(record.GetPropertyValue(property.Name));
if (!string.IsNullOrEmpty(value))
{
value = Sanitize(value);
record.SetPropertyValue(property.Name, value);
}
}
}
在这种情况下,我只会清理Person.PersonName
,但是,我还需要清理Address.StreetName
和Address.City
有没有办法编写这个lambda表达式来获取类型字符串的子类属性?我应该如何执行此操作以获取字符串类型的所有属性,以便我可以清理它们?
答案 0 :(得分:2)
好像你需要一个递归方法。
的伪代码:
public void SanitizeObject(object some)
{
// We get properties which are of reference types because we don't want to iterate value types (do you want to sanitize an integer...?)
foreach (PropertyInfo property in some.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(prop => !prop.PropertyType.IsValueType)
{
if (property.PropertyType == typeof (string))
{
// Do stuff to sanitize the string
}
else
{
// Get properties declared in the concrete class (skip inherited members)
var properties = property.DeclaringType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
// Does the property type has properties?
if (properties != null && properties.Length > 0)
{
// This gets the custom object and starts a recursion to sanitize its string properties if the object have string properties, of course...
SanitizeObject(property.GetValue(some));
}
}
}
}
请注意,我删除了通用参数。我相信,当你使用反射来获取属性进行消毒时,根本没有使用泛型的优势。使用这种方法,您将能够清理任何对象,而不仅仅支持实体类型。