[英]how to change an object type to its actual type?
我有一個實際上是字符串/整數的對象。 我可以通過 obj.GetType() 獲取它的類型。 在運行時我知道它是一個字符串。 問題是函數只接受字符串或整數。 如果我寫
int cnt = 0;
public object why()
{
cnt++;
if (cnt % 2 == 0) return 0;
return "";
}
void A(int input) {
}
void A(string input) {
}
void Test()
{
object obj = why();
MethodInfo method = obj.GetType().GetMethod(nameof(A), new[] { obj.GetType() });
//Need to call A by obj, but it threw an error :)
method.Invoke(null, new[] { obj });
}
它在拒絕對象時返回錯誤。 它可以工作,如果
func((string)obj)
但我還需要滿足整數(可能還有其他類型太晚了,因此可能不適合對場景應用條件語句)
最佳的方法是改變對象的類型,將其分配給函數之前,但我不知道這是否是可能的,這是字符串中的例子FUNC((字符串)目標文件)。
您可以使用反射根據對象的類型來獲取正確的方法。 然后您可以使用Invoke()
實際調用帶有參數的方法。
object obj = why();
MethodInfo method = typeof(YourClass).GetMethod(nameof(YourClass.A), new [] { obj.GetType() } );
method.Invoke(maybe_an_object_here, new [] { obj } );
YourClass
是包含方法A
的類。maybe_an_object_here
是您要在其上調用A
方法的YourClass
的對象實例。 根據您在做什么,這個參數可以是this
(如果它是YourClass
的對象)。 如果它是一個static
方法(它不是根據您提供的代碼),您不提供該類的對象,而是使用值null
因為您不需要對象來調用static
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.