How do I conditionally add a class with Add-Type -TypeDefinition if it isn't added already?

前端 未结 5 1268
我在风中等你
我在风中等你 2020-12-16 09:15

Consider the following PowerShell snippet:

$csharpString = @\"
using System;

public sealed class MyClass
{
    public MyClass() { }
    public override stri         


        
5条回答
  •  庸人自扰
    2020-12-16 09:48

    Actually, none of this is required. Add-Type maintains a cache of any code that you submit to it, along with the resulting type. If you call Add-Type twice with the same code, then it won't bother compiling the code and will just return the type from last time.

    You can verify this by just running an Add-Type call twice in a row.

    The reason you got the error message in the example above is that you changed the code between calls to Add-Type. While the solution above makes that error go away in this situation, it also means that you're working with an older definition of the type that probably isn't acting the way you think it is.

提交回复
热议问题