【问题标题】:Determine which properties in a class has a special attribute [duplicate]确定类中的哪些属性具有特殊属性[重复]
【发布时间】:2020-11-15 07:50:19
【问题描述】:

我有一个具有类似属性的类:

public List<Some1POCO> SomeProp1List{ set; get; }

[SomeAttribute]
public List<Some2POCO> SomeProp2List { set; get; }
.
.
.

我想找出具有“SomeAttribute”的属性,然后将此属性包含在 EF 查询中

如何在 LINQ 查询中使用它作为条件?

【问题讨论】:

  • 答案很可能是肯定的。
  • 看看here

标签: c# reflection


【解决方案1】:

如果TClass 恰好有一个带有SomeAttribute 的属性并且TProp 是引用类型,则此示例有效。

您可以像使用其他所有函数一样在 LINQ 查询中使用此函数。

TProp GetValueOfPropertyWithSomeAttribute<TClass, TProp>(TClass entity)
  where TClass : class
  where TProp : class
{
  return typeof(TClass)
    .GetProperties()
    .Single(pi => Attribute.IsDefined(pi, typeof(SomeAttribute), false))
    .GetMethod
    .Invoke(entity, null) as TProp;
}

【讨论】:

猜你喜欢
  • 2013-01-04
  • 1970-01-01
  • 1970-01-01
  • 2013-02-13
  • 2015-04-27
  • 2020-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多