【问题标题】:Get static property of class from generic type parameter从泛型类型参数获取类的静态属性
【发布时间】:2013-08-19 14:08:03
【问题描述】:

假设我有以下内容:

public class GetById<TEntity> : where TEntity : Entity
{
    public Guid EntityId { get; set; }

    public TEntity Execute()
    {
        // Get the entity here
    }
}

我想做的是检索通过 TEntity 传入的类的特定静态属性的值。此属性在 Entity 基类中不存在,但它作为任何不同派生类的属性存在,这些派生类将作为 TEntity 参数传入。我在 SO 上发现了类似的问题,但他们都假设该属性也在基类中声明。

有没有通过反射或类似的方法来做到这一点?这是一个 .NET 4.0 项目。

【问题讨论】:

    标签: c# .net generics reflection


    【解决方案1】:

    类型系统不允许您这样做。

    你可以使用反射:

    typeof(TEntity).GetProperty("MyProp", BindingFlags.Public | BindingFlags.Static)
    

    【讨论】:

      猜你喜欢
      • 2020-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-17
      • 2015-02-15
      • 2015-07-28
      相关资源
      最近更新 更多