我是创建 NuGet 包的新手,我在各种环境中运行了以下代码片段:
/// <summary>
/// Tries to find type by name in the executing assembly and after that
/// in referenced assemblies.
/// </summary>
/// <param name="typeName">Name of the type to find (can be full or assembly qualified name as well).</param>
/// <returns>Type found using the given name (or null if not found).</returns>
public static Type FindType(string typeName)
{
if (typeName == null) throw new ArgumentNullException(nameof(typeName));
// Helper method for finding the type in an assembly
Type Finder(Assembly ass) => ass?.GetTypes().FirstOrDefault(type =>
typeName.In(type.Name, type.FullName, type.AssemblyQualifiedName)
);
// Get the current assembly
var executingAssembly = Assembly.GetExecutingAssembly();
// Check if the type is inside the current assembly
var targetType = Finder(executingAssembly);
// Go through all of the referenced assemblies
foreach (var assName in executingAssembly.GetReferencedAssemblies())
{
// If the type was found, return it
if (targetType != null)
return targetType;
// Check if the type is inside the assembly
targetType = Finder(Assembly.Load(assName));
}
return null; // Type wasn't found, return null
}
如果我将其作为本地函数或通过引用的项目运行,它可以正常工作,但是当我创建 NuGet 包并使用 NuGet 包内的方法的实现来调用该方法时,它会返回 null。
方法
Assembly.GetExecutingAssembly
声称它返回 The assembly that contains the code that is currently executing
但从 NuGet 包运行它时我得到了不同的结果。
如果将方法打包到 NuGet 包中,我该怎么做才能从方法中获得正确的输出?