我正在制作一个辅助方法,该方法将自动为给定实体(类)的属性设置随机值,以便在测试时不必为每个属性填充值。

在我的情况下,每个实体都继承自BaseEntity类,该类具有ID,CreatedBy,CreatedOn等属性。基本上,此类具有所有实体之间共享的所有属性。

我要在这里完成的工作是将唯一属性与常见属性分开。

这是我的代码:

public static TEntity PopulateProperties<TEntity>(TEntity entity)
{
    try
    {
        // Since every entity inherits from EntityBase, there is no need to populate properties that are in EntityBase class
        // because the Core project populates them.
        // First of all, we need to get all the properties of EntityBase
        // and then exlude them from the list of properties we will automatically populate

        // Get all properties of EntityBase
        EntityBase entityBase = new EntityBase();
        List<PropertyInfo> entityBaseProperties = new List<PropertyInfo>();
        foreach (var property in entityBase.GetType().GetProperties())
        {
            entityBaseProperties.Add(property);
        }

        // Get all properties of our entity
        List<PropertyInfo> ourEntityProperties = new List<PropertyInfo>();
        foreach (var property in entity.GetType().GetProperties())
        {
            ourEntityProperties.Add(property);
        }

        // Get only the properties related to our entity
        var propertiesToPopulate = ourEntityProperties.Except(entityBaseProperties).ToList();

        // Now we can loop throught the properties and set values to each property
        foreach (var property in propertiesToPopulate)
        {
            // Switch statement can't be used in this case, so we will use the if clause
            if (property.PropertyType == typeof(string))
            {
                property.SetValue(entity, "GeneratedString");
            }
            else if (property.PropertyType == typeof(int))
            {
                property.SetValue(entity, 1994);
            }
        }

        return entity;
    }
    finally
    {
    }
}


问题在于var propertiesToPopulate = entityBaseProperties.Except(ourEntityProperties).ToList();

我期望的是只有该实体唯一的PropertyInfo对象的列表,但是我总是得到实体的所有属性。
此行未按预期过滤列表。

任何帮助,为什么?

最佳答案

另一种可能是在for循环中检查DeclaringType是否与entity的类型相同:

// Get all properties of our entity
List<PropertyInfo> ourEntityProperties = new List<PropertyInfo>();
foreach (var property in entity.GetType().GetProperties())
{
    // check whether it only belongs to the child
    if (property.DeclaringType.Equals(entity.GetType()))
    {
        ourEntityProperties.Add(property);
    }
}


然后,您只需要一个循环即可过滤掉所有必要的属性。

在“ linqish” oneliner中,您可以将其编写为:

List<PropertyInfo> ourEntityProperties = entity.GetType().GetProperties().Where(x=>x.DeclaringType.Equals(entity.GetType())).ToList();


但这看起来太可怕了;)

关于c# - List <PropertyInfo>,但List <PropertyInfo>无效,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42534855/

10-09 01:09