在使用泛型方法時,經常會遇到在編譯時不知道類型參數,而是在運行時動態確定類型參數的情況。反射提供了一種強大的解決方案來應對這一挑戰。
要使用存儲在myType變量中的類型調用泛型方法GenericMethod
使用反射獲取泛型方法的MethodInfo:
<code class="language-csharp">MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod));</code>
使用MakeGenericMethod提供類型參數來構造泛型方法:
<code class="language-csharp">MethodInfo generic = method.MakeGenericMethod(myType);</code>
調用構造的泛型方法:
<code class="language-csharp">generic.Invoke(this, null);</code>
要調用靜態泛型方法StaticMethod
獲取靜態泛型方法的MethodInfo:
<code class="language-csharp">MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.StaticMethod));</code>
使用類型參數構造泛型方法:
<code class="language-csharp">MethodInfo generic = method.MakeGenericMethod(myType);</code>
調用構造的泛型方法,由於它是靜態方法,因此將null作為第一個參數傳遞:
<code class="language-csharp">generic.Invoke(null, null);</code>
雖然反射為調用泛型方法提供了一個強大的解決方案,但它可能涉及相當多的樣板代碼。但是,從C# 4開始,您可以利用dynamic關鍵字來簡化此過程。如果類型推斷可用,使用dynamic可以顯著減少所需的代碼量。
以上是如何調用C#中動態分辨類型變量的通用方法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!