2017-08-30 8 views
0

呼び出された別のメソッドのクラス内にあるメソッドを呼び出そうとしています。C#呼び出しから返されたオブジェクトをキャストし、そのオブジェクトのメソッドを呼び出す

クラスからGetConnectionCost()メソッドを呼び出そうとしています。 ConnectionProfileオブジェクトは、NetworkInformationクラスからGetInternetConnectionProfileメソッドを呼び出すことによって返されました。私はめったにので、私は問題の専門家ではないですが、私はprofileオブジェクトをケースと呼び出すための方法を見つけようとしています私のコードにリフレクションを使用しない

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. 

:以下

は、これまでの私のコードですそれには GetConnectionCostメソッドがあります。

任意の提案

GetInternetConnectionProfile

答えて

1

は静的であるが、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 
      } 
関連する問題