Reputation: 4785
I am trying to invoke a method that is within the returned class of another invoked method.
I am trying to call the GetConnectionCost() method from the ConnectionProfile
class. The ConnectionProfile
object was returned by Invoking the GetInternetConnectionProfile
method from NetworkInformation class.
Below is my code so far:
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.
I rarely use reflection in my code so I am not an expert in the matter but I am trying to find a way to case the profile
object and invoke the GetConnectionCost
method on it.
Any suggestions
Upvotes: 0
Views: 56
Reputation: 4785
Found a solution:
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
}
Upvotes: 0
Reputation: 888
GetInternetConnectionProfile
is static, but GetConnectionCost
is an instance method.
You need to pass an instance to Invoke
Try this:
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);
You will still get back an object
.
You can cast it to dynamic
Upvotes: 1