C#打印TableEntity属性,但忽略具有属性[IgnoreProperty]的那些属性

我正在尝试打印出一个实现TableEntity类的对象,而没有那些关于持久性应该被忽略的对象。我通常用于打印对象的方法是使用StatePrinter。

public class MyEntity : TableEntity
{
    public string MyProperty { get; set; }

    [IgnoreProperty]
    public string MyIgnoredProperty { get; set; }

    public override string ToString()
    {
        Stateprinter printer = new Stateprinter();
        return printer.PrintObject(this);
    }
}

尽管这对于任何类型的类都非常有效,但使用此MyEntity类,它也会打印MyIgnoredProperty。打印出对象时,是否有聪明的方法也可以忽略具有[IgnoredProperty]作为属性的属性?

评论
Kennedy
Kennedy

You can configure what fields/properties the Stateprinter cares about by configuring what "field harvester" to use.

Here's a simple field harvester that only returns public properties without the 'IgnoreProperty' attribute.

class PersistencePropertiesHarvester : IFieldHarvester
{
    public bool CanHandleType(Type type)
    {
        return typeof(TableEntity).IsAssignableFrom(type);
    }

    public List<SanitizedFieldInfo> GetFields(Type type)
    {
        var fields = new HarvestHelper().GetFieldsAndProperties(type);
        return fields.Where(IsPerstistenceProperty).ToList();
    }

    private static bool IsPerstistenceProperty(SanitizedFieldInfo field)
    {
        return
            // Only return properties ...
            field.FieldInfo.MemberType == MemberTypes.Property          
            &&
            // ... that has a public get method ...
            (field.FieldInfo as PropertyInfo)?.GetGetMethod(false) != null
            &&
            // ... that does not have the IgnoreProperty attribute
            field.FieldInfo.GetCustomAttribute<IgnoreProperty>() == null
            ;           
    }
}

然后像这样使用它:

public class MyEntity : TableEntity
{
    public string MyProperty { get; set; }

    [IgnoreProperty]
    public string MyIgnoredProperty { get; set; }

    public override string ToString()
    {
        Stateprinter printer = new Stateprinter();
        printer.Configuration.Add(new PersistencePropertiesHarvester());
        return printer.PrintObject(this);
    }
}

And the result of new MyEntity().ToString() is now

new MyEntity()
{
    MyProperty = null
}
点赞
评论