[英]Loading assembly with reflection - 'object' does not contain a definition for 'Description'?
我们需要在运行时加载 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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.