C#强制转换从调用返回的对象并调用该对象上的方法
我试图调用另一个被调用方法的返回类中的方法 我试图从C#强制转换从调用返回的对象并调用该对象上的方法,c#,windows,reflection,C#,Windows,Reflection,我试图调用另一个被调用方法的返回类中的方法 我试图从ConnectionProfile类调用该方法。通过从NetworkInformation类调用GetInternetConnectionProfile方法,返回了ConnectionProfile对象 以下是我目前的代码: using System.Reflection; var t = Type.GetType("Windows.Networking.Connectivity.NetworkInformation, Windows, Co
ConnectionProfile
类调用该方法。通过从NetworkInformation类调用GetInternetConnectionProfile
方法,返回了ConnectionProfile
对象
以下是我目前的代码:
using System.Reflection;
var t = Type.GetType("Windows.Networking.Connectivity.NetworkInformation, Windows, ContentType=WindowsRuntime");
var profile = t.GetTypeInfo().GetDeclaredMethod("GetInternetConnectionProfile").Invoke(null, null);
var cost = profile.GetTypeInfo().GetDeclaredMethod("GetConnectionCost").Invoke(null, null); //This does not work of course since profile is of type object.
我很少在代码中使用反射,因此我不是这方面的专家,但我正试图找到一种方法来对profile
对象进行分类,并调用GetConnectionCost
方法
任何建议
GetInternetConnectionProfile
都是静态的,但GetConnectionCost
是一个实例方法
您需要将实例传递给Invoke
试试这个:
var t = Type.GetType("Windows.Networking.Connectivity.NetworkInformation, Windows, ContentType=WindowsRuntime");
var profile = t.GetMethod("GetInternetConnectionProfile").Invoke(null, null);
var cost = profile.GetType().GetMethod("GetConnectionCost").Invoke(profile, null);
您仍将获得一个对象
您可以将其强制转换为动态找到解决方案:
var networkInfoType = Type.GetType("Windows.Networking.Connectivity.NetworkInformation, Windows, ContentType=WindowsRuntime");
var profileType = Type.GetType("Windows.Networking.Connectivity.NetworkInformation, Windows, ContentType=WindowsRuntime");
var profileObj = networkInfoType.GetTypeInfo().GetDeclaredMethod("GetInternetConnectionProfile").Invoke(null, null);
dynamic profDyn = profileObj;
var costObj = profDyn.GetConnectionCost();
dynamic dynCost = costObj;
var costType = (NetworkCostType)dynCost.NetworkCostType;
if (costType == NetworkCostType.Unknown
|| costType == NetworkCostType.Unrestricted)
{
//Connection cost is unknown/unrestricted
}
else
{
//Metered Network
}
这正是我5秒钟前做的。谢谢你的回答