2014-10-30 53 views
-1

我有一个库类,设置插入元数据域对象的方法:如何检查和设置泛型类中特定值对象的值?

private void SetInsertMetadata(TDomainEntity entity) 
{ 
     entity.InsertDT = DateTime.UtcNow; 
} 

我需要检查 - 这是否entity类具有为属性值对象的列表?如果是,则在其中的每一个中设置InsertDT

如何从泛型类中进行此检查?

+1

是否'TDomainEntity'实现定义的相关属性的界面? – 2014-10-30 14:55:03

+0

您是否在说,如果'entity.SomeProperty'也实现了'TDomainEntity',那么还要在其上设置'InsertDT'属性? – DavidG 2014-10-30 14:56:05

+0

如果你不能依赖一个接口,你可以委托给类本身(!)或使用Reflection(!!!) – 2014-10-30 14:56:33

回答

2

这里做一些假设。首先,你的界面看起来是这样的:

public interface TDomainEntity 
{ 
    DateTime InsertDT { get; set; } 
} 

而且你有一对夫妇的实体:

public class EntityA : TDomainEntity 
{ 
    public EntityB BValue { get; set; } 
    public DateTime InsertDT { get; set; } 
} 

public class EntityB : TDomainEntity 
{ 
    public DateTime InsertDT { get; set; } 
} 

你的函数来遍历每个属性和设置InsertDT属性可能是这样的:

private void SetInsertMetadata(TDomainEntity entity) 
{ 
    if(entity == null) return; //To prevent errors below 

    entity.InsertDT = DateTime.UtcNow; 

    //Get all properties of the entity that also implement the TDomainEntity interface 
    var props = entity.GetType().GetProperties() 
        .Where(p => typeof(TDomainEntity).IsAssignableFrom(p.PropertyType)); 

    //Recurse through each property: 
    foreach(var p in props) 
    { 
     SetInsertMetadata((TDomainEntity)p.GetValue(entity)); 
    } 
} 

或者你可以合并这最后几行一起:

entity.GetType().GetProperties() 
    .Where(p => typeof(TDomainEntity).IsAssignableFrom(p.PropertyType)) 
    .ToList() 
    .ForEach(p => SetInsertMetadata((TDomainEntity)p.GetValue(entity))); 

如果您还希望包括IEnumerable<TDomainEntity>性质,补充一点:

entity.GetType().GetProperties() 
    .Where(p => typeof(IEnumerable<TDomainEntity>).IsAssignableFrom(p.PropertyType)) 
    .ToList() 
    .ForEach(p => 
    { 
     var value = (IEnumerable<TDomainEntity>)p.GetValue(entity); 
     if(value == null) return; 
     value.ToList().ForEach(i => SetInsertMetadata((TDomainEntity)i)); 
    }); 
+0

谢谢!如果EntityA拥有IList 的财产,请帮助我提高代码质量吗? – bonafiden 2014-10-30 16:31:19

+0

你的工作如何?当然没有测试过! – DavidG 2014-10-30 17:00:28

+0

是的,它解决了 - 非常感谢! – bonafiden 2014-10-30 21:02:21

0

假设你的类定义看起来有点像:从接口

public class GenericClass<TDomainEntity> 
{ 
    ... 
} 

你想指定TDomainEntity继承。创建一个看起来像这样的接口:

public interface IDateTimeHolder 
{ 
    DateTime InsertTD { get; set; } 
} 

(命名接口,但是你想) 然后更新您的泛型类指定泛型类型的接口:

public class GenericClass<TDomainEntity> where TDomainEntity : IDateTimeHolder 
{ 
    string Version { get; set; } 
} 

也可确保传入的类实现接口。