c# - 使用反射加载程序集 - “对象”不包含“描述”的定义?
问题描述
我们需要在运行时加载 mongodb c# 程序集。
(原因:通过 nuget 附加到应用程序的运行状况检查服务,需要检查应用程序的 mongo 连接性,但它应该使用 BIN 中现有的(!)mongo dll。没有自带一个,因此通过反射加载 mongo)
我需要检查的是这段代码:
MongoClient client = new MongoClient(mongoConnection);
var res = client.Cluster.Description.State == ClusterState.Connected;
我已经成功完成了第一部分:
Assembly dll = Assembly.LoadFile(@"C:\Users\RoyiNamir\....\MongoDB.Driver.dll");
Type type = dll.GetType("MongoDB.Driver.MongoClient");
Console.WriteLine(type); //MongoDB.Driver.MongoClient
dynamic client = Activator.CreateInstance(type, mongoConnection);
Console.WriteLine(client.Cluster.Description );
我在最后一行出现异常,我尝试打印client.Cluster.Description
:
Message
'object' does not contain a definition for 'Description'
Source
Anonymously Hosted DynamicMethods Assembly
StackTrace
at CallSite.Target(Closure , CallSite , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at UserQuery.Main()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
但是 - 如果我 Console.WriteLine(client.Cluster);
改为执行,那么我会得到结果:
使用反射器,我看到描述是:
ClusterDescription Description { get; }
public sealed class ClusterDescription : IEquatable<ClusterDescription> {}
问题:
为什么会抛出异常?
使用动态/反射,我如何访问该Description
属性?
解决方案
这是因为该类Description
显式地实现了该属性。因此,您的代码应该看起来像这样才能修复它。也就是说,您需要显式转换为正确的接口。
dynamic c =Activator.CreateInstance(type);
Console.WriteLine(((ICluster)c.Cluster).Description);
或者您可以使用如下所有动态:
dynamic c =Activator.CreateInstance(type);
var targetType = type.GetProperties().Where(x => x.Name == "Cluster").Single().PropertyType;
Console.WriteLine(targetType.GetProperty("Description").GetValue(c.Cluster));
推荐阅读
- android - 无法在 Android 上接收 Pushy 推送通知
- php - 使链接在 30 分钟后或使用后无效
- angular6 - Angular 6 文件上传与其他表单数据
- visual-studio-code - VS Code 是否有一个热键来翻转表达式(例如“a && b”到“b && a”)?
- c# - 如何使用实体框架在 C#、ASP.NET MVC 3 中获取两个日期之间的记录?
- kubernetes - 指定 --nodes、master-size 等选项时,Jenkins-x 集群设置失败
- python - 在 Python 中合并多个 .txt/csv 文件
- java - 观察到调试 OOM 错误
- python-3.x - Python - 无法计算数据框中定义范围内值的出现次数
- javascript - 是否有可能第一个参数是可选的,而第二个参数在 Javascript 的函数中是强制性的?