2014-05-21 37 views
1

我遇到了問題。我是一名VB.net程序員,我正在努力學習C#。在我已經完成的很多VB項目中,我總是使用一個viewModelBase類,在那裏我可以通過我的項目通知我的屬性,當我嘗試將代碼從vb轉換爲C#時,我得到一個method name expected就行了:if (TypeDescriptor.GetProperties(this)(propertyName) == null)c#方法名稱預計INotifypropertyChanged

[Conditional("DEBUG"), DebuggerStepThrough()] 
    public void VerifyPropertyName(string propertyName) 
    { 
     if (TypeDescriptor.GetProperties(this)(propertyName) == null) 
     { 
      string msg = "Invalid property name: " + propertyName; 

      if (this.ThrowOnInvalidPropertyName) 
      { 
       throw new Exception(msg); 
      } 
      else 
      { 
       Debug.Fail(msg); 
      } 
     } 
    } 

我真的找不到任何解決方案!任何幫助?

謝謝

+0

雙括號似乎真的了。你只能調用一個函數,所以你應該只有一個函數。也許你打算使用逗號'GetProperties(this,propertyName)'? – BradleyDotNET

+0

@BradleyDotNET'TypeDescriptor.GetProperties()'沒有重載,它需要一個'object'和一個'string'。 –

+0

你期望* TypeDescriptor.GetProperties(this)(propertyName)'做什麼? –

回答

6

這聽起來像你只是缺少一個事實,即在C#索引語法[key]。我懷疑你想:

if (TypeDescriptor.GetProperties(this)[propertyName] == null) 

這是第一次調用GetProperties方法,找到this所有屬性的PropertyDescriptorCollection ......然後它使用的PropertyDescriptorCollectionindexer通過名稱來訪問一個特定的屬性。

+0

我忘了VB使用()進行數組索引。接得好! – BradleyDotNET

+0

是的,這就是它在C#中的索引是用[]和不是()完成的..好吧,我真的必須把它放在我的腦海!謝謝。 – Rui

0

你也可以使用 「查找」 功能:

if (TypeDescriptor.GetProperties(this).Find(propertyName, false) == null) 

MSDN

注意這並區分大小寫的發現。

+0

謝謝你的回答,但@Jon Skeet有一個更好的答案! – Rui

+0

@Rui,沒問題,我同意他的方法更好,但在我的研究中發現了這種方法,所以我想我會分享!很高興你解決了你的問題。 – BradleyDotNET

0

試試這個:

[Conditional("DEBUG"), DebuggerStepThrough()] 
    public void VerifyPropertyName(string propertyName) 
    { 
     PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(this); 
     var objValue = properties[propertyName].GetValue(this); 
     if (objValue == null) 
     { 
      string msg = "Invalid property name: " + propertyName; 

      if (this.ThrowOnInvalidPropertyName) 
      { 
       throw new Exception(msg); 
      } 
      else 
      { 
       Debug.Fail(msg); 
      } 
     } 
    }