【发布时间】:2021-12-25 21:27:45
【问题描述】:
我有一个加载程序集并按属性对数据进行分类的代码。
我正在尝试获取实际的 CustomAttribute 对象。 在网络框架上调试期间,代码返回一个值。 在 .Net5 上运行代码返回 null
编辑 在对文档进行了一些挖掘之后:
.NET Framework 2.0 版提供了一个新的加载上下文,即仅反射上下文,可用于检查无法加载执行的代码。
https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/accessing-custom-attributes
编辑#2 原因是我试图在运行时获取对象,并且正如上面引用的文档中所写,无法加载属性以及任何其他运行时仅反射上下文,并且该方法返回 null。
除了使用 system.reflection 在运行时获取实际属性对象之外,还有其他解决方案吗?
字典初始化
var ass = Assembly.LoadFile(Path.GetFullPath("MyInterface.dll"));
var asss = Assembly.GetExecutingAssembly();
var apiInterfaces = ass.DefinedTypes.Where(x => x.IsInterface && x.CustomAttributes != null && x.CustomAttributes.Any(z => z.AttributeType.FullName != null && z.AttributeType.FullName.Equals(typeof(ApiInterfaceDescriptorAttribute).FullName)));
属性:
[AttributeUsage(AttributeTargets.Interface)]
public class ApiInterfaceDescriptorAttribute : Attribute
{
public string ApiUsageName { get; }
public ApiInterfaceDescriptorAttribute(string apiUsageName)
{
ApiUsageName = apiUsageName;
}
}
示例界面
[ApiInterfaceDescriptor("powercontrol")]
public interface IMyInterface
{
[ApiMethodDescriptor(ApiExposureLevel.Basic, "a-method...")]
void SomeMethod();
}
获取属性的试炼
public class ApiDetector
{
private Dictionary<Type, List<MethodInfo>> _apiDictionary = new Dictionary<Type, List<MethodInfo>>();
public void LoadApiElements()
{
var apiKeyDesriptor = key.GetCustomAttribute(typeof(ApiInterfaceDescriptorAttribute)) as ApiInterfaceDescriptorAttribute;
_apiDetector.Add(new ApiDataObjectDescriptor { Name = key.Name, ApiUsageName = apiKeyDesriptor?.ApiUsageName, Type = key });
}
}
在.Net5远程机器上运行代码返回null:
欢迎任何帮助。 先谢谢了!
【问题讨论】:
-
This minimal code 在 .NET5 和 6 中似乎可以正常工作。“远程机器”是什么意思(您是通过远程调试来实现的)?你确定是 .NET5 的错吗?
-
GetCustomAttribute 上有第二个参数 - bool 继承。不确定这是否与您的问题有关,但您可以考虑在其中传递
true。 -
@Vic F - 我也尝试了第二个参数...
-
@NPras - 我更新了帖子,它与远程机器无关,我也在 .Net 5 bin 调试文件夹下本地检查了标准调试,并收到了相同的结果。我还添加了字典初始化,它可能是最小代码之间的差异。有什么想法吗?
-
到那时您是否检查过 Dictionary 是否确实包含任何内容?也许逐步检查填充字典的方法,看看它是否没有正确加载。
标签: c# reflection attributes runtime .net-5