使用Resharper 7.1插件从IClass中删除IProperty

时间:2013-08-08 08:17:08

标签: c# resharper-7.1 resharper-plugins

我想创建一个resharper插件,它从类中删除带有返回类型字符串的属性。我已经创建了一个IActionHandler来获取所选类的所有属性,但我不知道如何修改代码结构以从类中删除属性

这是IActionHandler

的执行方法
public void Execute(IDataContext context, DelegateExecute nextExecute)
{
    // Fetch active solution from context.
    ISolution solution = context.GetData(JetBrains.ProjectModel.DataContext.DataConstants.SOLUTION);
    if (solution == null)
        return;

    var declaredElements = context.GetData(DataConstants.DECLARED_ELEMENTS);
    if (declaredElements == null || declaredElements.IsEmpty())
        return;

    IDeclaredElement declaredElement = declaredElements.First();

    var classElement = declaredElement as IClass;
    if (classElement != null)
    {
        var properties = classElement.Properties.Where(p => p.Type.IsString());

        foreach (IProperty property in properties)
        {
            // Remove IProperty from IClass   <--
        }
    }
}

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我找到了答案:

public void Execute(IDataContext context, DelegateExecute nextExecute)
{
    // Fetch active solution from context.
    ISolution solution = context.GetData(JetBrains.ProjectModel.DataContext.DataConstants.SOLUTION);
    if (solution == null)
        return;

    var declaredElements = context.GetData(DataConstants.DECLARED_ELEMENTS);
    if (declaredElements == null || declaredElements.IsEmpty())
        return;

    IDeclaredElement declaredElement = declaredElements.First();

    var classElement = declaredElement as IClass;
    if (classElement != null)
    {
        // As a class can be declared in multiple files (partial classes) we enumerate all
        // declarations and choose the first one
        var declarations = classElement.GetDeclarations();
        var classDeclaration = declarations.First() as IClassDeclaration;

        var properties = classDeclaration.PropertyDeclarations.Where(p => p.Type.IsString());

        foreach (var propertyDeclaration in properties)
        {       
            PsiManager.GetInstance(solution).DoTransaction(() =>
            {
                classDeclaration.RemoveClassMemberDeclaration(propertyDeclaration);
            },
            "PsiTransactionCommand");
        }
    }
}