How to access the specified Add-Type in another Add-Type definition?

How to access a type defined Add-Type -TypeDefinition "..."in another Add-Type -TypeDefinition "..."?

In the following code example, despite the same namespace, the compiler cannot find the type UserCode.

Add-Type -TypeDefinition @"
namespace SampleCode {
    public struct UserCode {
         public string Name;
         public string Id;
    }
}
"@

#.... do something ....

Add-Type -TypeDefinition @"
namespace SampleCode {
    public struct UserInformation {
        public UserCode User;
        public string Note;
    }
}
"@
# => Error ... Add-Type : <temporary source path>(3) : The type or namespace name
# 'UserCode' could not be found (are you missing a using directive or an assembly
# reference?)
+4
source share
2 answers

To reference the first .NET assembly from the second .NET assembly, you need to transfer the first .NET assembly to disk. Once you do this, you can reference the first .NET assembly from the second .NET assembly using the -ReferencedAssembliescmdlet parameter Add-Type.

. #, , using .

, , :

  • .NET
  • ,

1 - # 1

.NET , . -OutputAssembly -OutputType Add-Type.

$Csharp = @"
using System;
using System.Reflection;

namespace Widget {
    public class UserCode {
        public static int GetValue() {
            return 2;
        }
    }
}
"@

# Define the output path for the new .NET Assembly
$OutputAssembly = '{0}\Widget.dll' -f $env:USERPROFILE;

# Compile the code and output a new .NET assembly
Add-Type -TypeDefinition $Csharp -OutputAssembly $OutputAssembly -OutputType Library;

# Load the .NET Assembly 
[System.Reflection.Assembly]::LoadFile($OutputAssembly);

2 - № 2

.NET , - . Add-Type, . , -ReferencedAssemblies .NET, 1.

# Now that we have a compiled .NET Assembly, we need to write our new code
# that references it (make sure to include all appropriate C# "using" statements)

# Define the second set of C# code
$CsharpCode2 = @"
using Widget;

namespace NASA {
    public class Shuttle {
        public int Boosters;
        public Shuttle() {
            this.Boosters = UserCode.GetValue();
        }
    }
}
"@;

# Try to compile the new code, but wait, we get an error ...
# ... because this code is dependent on the code contained in the
# Widget assembly
$Assembly2 = Add-Type -TypeDefinition $CsharpCode2 -PassThru;

# We have to reference the .NET Assembly that defines the UserCode type
$Assembly2 = Add-Type -TypeDefinition $CsharpCode2 -ReferencedAssemblies $OutputAssembly -PassThru;

# Now we can successfully create the NASA.Shuttle object;
$Shuttle = New-Object -TypeName NASA.Shuttle;

# View the number of boosters the Shuttle instance has
Write-Host -Object $Shuttle.Boosters;
+7

( , .)

dll Add-Type , :

Add-Type -OutputAssembly foo1.dll ...
Add-Type -ReferencedAssemblies foo1.dll ...

.

+1

All Articles