2016-03-13 53 views
2

我目前正在從this video瞭解約Reflection後期綁定。爲什麼string []被解釋爲object [],而不是對象,但我們可以分配object obj = new string []?

而當我複製視頻中的代碼時,有一部分令我感到困惑。這是當使用Invoke方法:

MethodInfo getFullNameMethod = customerType.GetMethod("GetFullName"); 
string[] parameters = new string[2]; 
parameters[0] = "First"; 
parameters[1] = "Last"; 

//here is where I got confused... 
string fullName = (string)getFullNameMethod.Invoke(customerInstance, parameters); 

據我可以看到(也顯示在視頻)Invoke具有(object, object[])輸入參數和無重載方法與輸入參數(object, object)

這裏通過的是(object, string[])。所以,起初我預計會有編譯錯誤,因爲我認爲string[]object而不是object[]。但是......沒有編譯錯誤。

那我迷惑不解:爲什麼string[]是一個object[]而非object(每Type是C#從object畢竟派生)?難道我們不能像這樣分配string[]嗎?

object obj = new string[3]; //this is OK 

可以一string[]如何既objectobject[]?使用其他數據類型,比如說int,作爲一個類比,我永遠不會期望變量爲intint[]在同一時間。

有人可以啓發我嗎?


Here is my full code: 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Reflection; 

namespace ConsoleApplication2 { 
    class Program { 
     static void Main(string[] args) { 
      Assembly executingAssembly = Assembly.GetExecutingAssembly(); 
      Type customerType = executingAssembly.GetType("ConsoleApplication2.Customer"); 
      object customerInstance = Activator.CreateInstance(customerType); 
      MethodInfo getFullNameMethod = customerType.GetMethod("GetFullName"); 
      string[] parameters = new string[2]; 
      parameters[0] = "First"; 
      parameters[1] = "Last"; 
      string fullName = (string)getFullNameMethod.Invoke(customerInstance, parameters); 
      Console.WriteLine(fullName); 
      Console.ReadKey(); 
     } 
    } 

    class Customer { 
     public string GetFullName(string FirstName, string LastName) { 
      return FirstName + " " + LastName; 
     } 
    } 
} 
+3

首先,每一個'class'和'struct'在.NET(包括每個陣列)最終從'object'派生,所以'string []'可以轉換爲'object'。其次,爲了與Java兼容,.NET中的數組是「協變的」,這意味着如果X具有對Y的引用轉換,那麼可以將類型X的數組轉換爲Y類型的數組。因爲'string'派生自'object' ,'string []'可以轉換爲'object []'。 –

+0

@MichaelLiu應該是答案! :)你能解釋一下更多關於「與Java的兼容性,.NET中的數組是否協變」?因爲我對Java不太熟悉.. – Ian

+1

Eric Lippert有一個簡短的博客文章,談論它:https://blogs.msdn。microsoft.com/ericlippert/2007/10/17/covariance-and-contravariance-in-c-part-two-array-covariance/ –

回答

1

據部分12.5在MSDN

對於任何兩個引用類型A和B,如果隱式引用 轉換(第6.1.4節)或顯式引用轉換(節 6.2.3)存在於從A到B,則從陣列類型A [R]到陣列類型B [R]也存在相同的參考轉換,其中R是給定秩指定符的任何 (但兩者都相同數組類型)。 這個 關係被稱爲陣列協方差

下面的代碼是完全有效的。

string[] items = new string[] {"A", "B", "C"};  
object[] objItems = items; 

這就是爲什麼在你的情況下,傳遞string[]是有效的,將被轉換爲object[]

+0

謝謝,解釋。 :) – Ian

+0

@我很高興:-) –

相關問題