Microsoft.Build.Evaluation的正确用法是什么? [英] What's the correct usage of Microsoft.Build.Evaluation?

查看:153
本文介绍了Microsoft.Build.Evaluation的正确用法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式将导入"添加到MSBuild项目.这个Microsoft.Build.Evaluation命名空间中的API允许我做到这一点(我更希望通过VS可扩展性API达到相同的结果,但是似乎没有任何方法可以做到这一点,所以我求助于该API)

I want to programmatically add an Import to an MSBuild project. The API in this Microsoft.Build.Evaluation namespace allows me to to this (I'd prefer to achieve the same result through the VS extensibility API but there doesn't seem to be any way to do that so I'm resorting to this API).

如果要在一个方法中打开一个或多个项目,请查看其导入",有时还要添加一个导入,我应该如何使用ProjectCollection对象?我是否总是创建一个新的ProjectCollection,将项目加载到其中,然后在方法末尾全部卸载?

If I want to open one or more Projects in a method, look at their Imports, and sometimes add an import, how am I supposed to use ProjectCollection object? Do I always create a new ProjectCollection, load projects into it, then unload them all at the end of the method?

我有满足我要求的工作代码,我只是猜不到如何正确地"使用此API,因为仅提供了通常的低级参考文档.

I have working code that does what I want, I just can't guess how to 'properly' use this API since there's just the usual low-level reference documentation provided.

推荐答案

好吧,在任何地方都找不到关于如何使用此API的任何建议的情况下,无论何时我想使用一个新的ProjectCollection都最终创建了一个新的ProjectCollection.项目对象,然后在ProjectCollection上调用UnloadAllProjects.

Well, in the absence of any advice anywhere I could find on how to use this API I ended up creating a new ProjectCollection any time I wanted to work with a project object, then calling UnloadAllProjects on the ProjectCollection.

/// <summary>
///  Do something with a Microsoft.Build.Evaluation.Project.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="projectPath"></param>
/// <param name="worker"></param>
/// <returns></returns>
static T WithProject<T>(string projectPath, Func<Project, T> worker)
{
    var pc = new ProjectCollection();
    try
    {
        if (string.IsNullOrWhiteSpace(projectPath))
            return default(T);
        var evalProject = pc.LoadProject(projectPath);
        return worker(evalProject);
    }
    catch
    {
        return default(T);
    }
    finally
    {
        pc.UnloadAllProjects();
    }
}

或者,更简单(从使用ILSpy窥探别人的DLL):

Or, much simpler (from snooping in somebody else's DLL with ILSpy):

public static Project GetMSBuildProject(string projectPath)
{
    Project project = null;
    if (project == null)
    {
        project = new Project(projectPath, new Dictionary<string, string>(), "12.0", new ProjectCollection());
    }
    return project;
}

这篇关于Microsoft.Build.Evaluation的正确用法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆