【问题标题】:Can ReSharper live templates do conditional code generation?ReSharper 实时模板可以进行条件代码生成吗?
【发布时间】:2012-08-26 17:10:44
【问题描述】:

示例:我想要一个插入方法的模板。如果该类被声明为sealed,那么我希望该方法被声明为private。如果类不是sealed,那么我希望将方法声明为protected virtual

另一个例子。如果类被继承,并且超类包含方法X,则调用base.X();,否则什么都不做。

这种类型的条件处理在 ReSharper 中可用吗?我想这已经接近 T4 领域,但能够在 Live Templates 中做到这一点真的很方便。

以防万一,我使用的是 R# 7。

详细场景

这两个要求都来自尝试为 IDisposable 模式编写实时模板(请参阅Implementing the Disposable Pattern Correctly)。生成的代码需要根据类是基类还是子类而有所不同。可以定义两个模板,但不难想象其他有用的场景。这是我的 IDisposable 模板中的代码:

#region IDisposable Pattern
    /// <summary>
    ///   Finalizes this instance (called prior to garbage collection by the CLR)
    /// </summary>
    ~$ClassName$() {
    Dispose(fromUserCode: false);
    }

public void Dispose()
{
    Dispose(fromUserCode: true);
    GC.SuppressFinalize(this);
}

private bool disposed = false;

// Declare as private if this class is sealed.
protected virtual void Dispose(bool fromUserCode)
{
    if (!disposed)
    {
        if (fromUserCode)
        {
            // ToDo - Dispose managed resources (call Dispose() on any owned objects).
            // Do not dispose of any objects that may be referenced elsewhere.
        }

        // ToDo - Release unmanaged resources here, if necessary.
    }
    disposed = true;

    // ToDo: Call the base class's Dispose(Boolean) method, if available.
    // base.Dispose(fromUserCode);
}
#endregion

【问题讨论】:

  • 我看不出sealed protected 的意义。密封类不能被继承,所以protected 毫无意义。也可以是private
  • 同意 - 这是一个错字。应该是私人的。已经更新了。但这只是一个人为的例子,不要太从字面上解释它。我只想知道是否有办法在 R# 实时模板中有条件地做事。

标签: resharper live-templates


【解决方案1】:

您当然可以这样做。您需要的是一个插件,它实现了执行实际检查的相应live template macro

【讨论】:

  • 谢谢 Dmitri - 一个简单明确的答案。喜欢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-13
  • 1970-01-01
相关资源
最近更新 更多