2017-08-30 18 views
0

我想調用另一個調用方法的返回類中的方法。C#鑄造從調用返回的對象並調用該對象上的方法

我想從ConnectionProfile類中調用GetConnectionCost()方法。通過調用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方法就可以了。

任何建議

回答

1

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); 

你仍然會得到回一個object

你可以將它轉換爲dynamic

+0

這正是我所做的5秒前。感謝你的回答 –

0

找到了解決辦法:

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 
      }