问题描述
我想轻松扩展我的 BaseClass 并在运行时自动将某些集合属性设为 Lazy,这些属性已标记为 [SubEntityCollection] 属性。
我已经编写了一个 GetSubEntityCollection 方法,除了从我的 BaseClass 派生的 T 类型,并返回一个 List
现在,我想以编程方式将此 Lazy 函数分配给它们可能存在于 MyClass(甚至在 BaseClass 级别)上的具有 [SubEntityCollection] 属性的任何其他属性,例如 MyClass.LazyItems
public abstract class BaseClass
{
public virtual Guid Id { get; protected set; }
public string Name { get; set; }
internal List<T> GetSubEntityCollection<T>(Guid parentEntityId) where T : BaseClass,new()
{
if (parentEntityId == null) { return null; }
try
{
//find the property tagged [ParentEntityId]
var ParentIdProp = typeof(T).GetProperties().Where(
p => System.Attribute.IsDefined(p,typeof(ParentEntityIdAttribute))).First();
List<T> collection = new GeneralRepository().GetAll<T>(x =>
(Guid)ParentIdProp.GetValue(x,null) == parentEntityId);
return collection;
}
catch { return null; }
}
}
public class Item : BaseClass
{
public override Guid Id { get; protected set; }
[ParentEntityId]
public Guid ParentId { get; set; }
}
public class MyClass : BaseClass
{
public override Guid Id { get; protected set; }
public List<Item> Items => new Lazy<List<Item>>(() => GetSubEntityCollection<Item>(this.Id)).Value;
[SubEntityCollection]
public List<Item> LazyItems { get; set; }
}
我可以将它添加到 MyClass 以获取一个新实例,该实例循环遍历属性以检查 [SubEntityCollection]。
public MyClass()
{
// find all SubEntityCollections and give them a Lazy value
foreach (var property in this.GetType().GetProperties().Where(
p => System.Attribute.IsDefined(p,typeof(SubEntityCollectionAttribute))))
{
property.SetValue(this,new Lazy<List<T>>(() => GetSubEntityCollection<T>(this.Id)));
}
}
我的问题是让下一部分工作。我想不出正确设置 GetSubEntityCollection 类型的方法。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)