如何解决我可以在运行时使属性 Lazy 吗?
我想轻松扩展我的 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 举报,一经查实,本站将立刻删除。