【问题标题】:using a Custom Attribute in C# for decorating method result在 C# 中使用自定义属性来装饰方法结果
【发布时间】:2011-01-13 03:22:05
【问题描述】:
  public IQueryable<T> All()
    {
        var session = _sessionFactory.GetCurrentSession();
        return FilterByClientId(from r in session.Query<T>() select r);
    }

    public IQueryable<T> FilterByClientId(IQueryable<T> queryable)
    {
        return queryable.Where(row => _clientIds.ClientIds.Contains<long>(row.ClientId) );
    }

我可以在方法上使用自定义属性来处理装饰吗?生成的代码看起来像这样。使用 ClientFilter 调用 All 方法会自动修饰结果。

[ClientFilter]
    public IQueryable<T> All()
    {
        var session = _sessionFactory.GetCurrentSession();
        return from r in session.Query<T>() select r;
    }

【问题讨论】:

    标签: c# decorator custom-attributes


    【解决方案1】:

    您正在寻找PostSharp,它允许您使用属性修改方法行为。

    但是,它会增加巨大的复杂性,并且对于这么简单的事情可能不值得。

    【讨论】:

      【解决方案2】:

      如果我明白你在问什么,那么答案可能是肯定的,但是使用属性的复杂性是不值得的。让你的第二个代码示例如下所示不是更简单吗?

      // Edited to make more sense, but see below...
      public IQueryable<T> FilterByClientId()
      {
          return All().Where(row => _clientIds.ClientIds.Contains<long>(row.ClientId) );
      }
      

      编辑:根据您的评论,尝试将 FilterByClientId 定义为具有通用约束的扩展方法:

      public static IQueryable<T> FilterByClientId(this IQueryable<T> queryable) where T : IHasClientId
      {
          return queryable.Where(row => _clientIds.ClientIds.Contains<long>(row.ClientId) );
      }
      

      【讨论】:

      • 我希望能够将 ClientFilter 应用于返回 IQueryable where T:IHasClientID 的几种方法
      猜你喜欢
      • 2011-07-11
      • 2013-04-10
      • 1970-01-01
      • 2018-07-20
      • 1970-01-01
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 2012-02-15
      相关资源
      最近更新 更多