public object GetObjectToSerialize(object value, Type targetType)
{
var allProperties = value.GetType().GetProperties();
var passwordProperties = allProperties.Where(p => p.PropertyType == typeof(string))
.Where(p => p.Name.Contains("Password"))
.ToList();
var passwordWithoutEncryptedAttribute = passwordProperties
.Where(p => !p.GetCustomAttributes(typeof(EncryptedConfigurationItemAttribute), false).Any());
if (passwordWithoutEncryptedAttribute.Any())
{
throw new InvalidOperationException(SafeFormatter.Format(BackgroundJobsLocalization.Culture, BackgroundJobsLocalization.PasswordWithoutEncryptedAttribute));
}
foreach (var property in passwordProperties)
{
property.SetValue(value, null, null);
}
return value;
}
我经常使用这种方法。如何优化它?因为据我所知,value.GetType().GetProperties();
会递归地工作(对于基本对象,然后对于基本对象的属性,接着是每个基本对象属性的属性等等)。
foreach
中将Password
属性的值设置为null
了吗? - xanatos