Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#强制转换从调用返回的对象并调用该对象上的方法_C#_Windows_Reflection - Fatal编程技术网

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秒钟前做的。谢谢你的回答