我在 C# 中加载了一个程序集。假设以下 csproj 有一个名为 OtherPackage 的 nuget 包引用。
项目A
ProjectB 在项目 A 的程序集中加载。我现在想检查 ProjectA 包引用 OtherPackage 是否等于 ProjectB 包引用 OtherPackage(如 1.0.0 == 2.0.0)。
我有一些代码
public class Program
{
public static void Main(string[] args)
{
var aAssembly = Assembly.LoadFrom("path to assembly a .dll");
var bAssembly = Assembly.GetExecutingAssembly();
// not sure where, if possible, to see the package reference versions here?
if (versionA != versionB)
{
// do something here
}
}
}
我尝试检查 Assembly 类中的属性,但找不到任何内容
使用
GetReferencedAssemblies()
方法,您可以检索程序集中引用的所有程序集作为 AssemblyName
对象数组,请参阅:https://learn.microsoft.com/en-us/dotnet/api/system.reflection。 assembly.getreferencedassemblies?view=net-8.0.
AssemblyName
的对象具有诸如Name
,Version
,...等属性。
这样就可以获得程序集中每个引用程序集的版本。
以下代码可能对所描述的问题有帮助:
public class Program
{
//Get referenced package as name version key value pairs
static Dictionary<string, Version> GetPackageReferenced(Assembly assembly) {
return assembly.GetReferencedAssemblies()
.ToDictionary(assembly => assembly.Name, assembly => assembly.Version);
}
static void Main(string[] args)
{
Assembly firstAssembly = Assembly.LoadFrom("<path of first assembly>");
Assembly secondAssembly = Assembly.LoadFrom("path of second assembly>");
Dictionary<string, Version> firstReferencedAssemblies = GetPackageReferenced(firstAssembly);
Dictionary<string, Version> secondReferencedAssemblies = GetPackageReferenced(secondAssembly);
AssemblyName assemblyName = new AssemblyName();
//Combine all reference assemblies in one collection
HashSet<string> allReferencedAssemblies = [.. firstReferencedAssemblies.Keys];
allReferencedAssemblies.UnionWith(secondReferencedAssemblies.Keys);
foreach (string assembly in allReferencedAssemblies)
{
if (!firstReferencedAssemblies.ContainsKey(assembly)|| !secondReferencedAssemblies.ContainsKey(assembly))
{
Console.WriteLine($"The refernced package is not shared");
}
else
{
if (firstReferencedAssemblies[assembly] != secondReferencedAssemblies[assembly])
{
Console.WriteLine("Referenced assemblies do NOT have the same version");
}
else
{
Console.WriteLine("Referenced assemblies have the same version");
}
}
}
}
}