这可以通过自己创建自定义属性来实现,例如:
[AttributeUsage(AttributeTargets.Property)]
public class TextSampleAttribute : Attribute
{
public string Value { get; set; }
public TextSampleAttribute(string value)
{
Value = value;
}
}
然后像这样修改SetPublicProperties
方法ObjectGenerator
:
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.IsDefined(typeof (TextSampleAttribute), false))
{
object propertyValue = property.GetCustomAttribute<TextSampleAttribute>().Value;
property.SetValue(obj, propertyValue, null);
}
else if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
我添加了一项检查以查看是否定义了 TextSampleAttribute,如果是,则使用它的值而不是自动生成的值。