2014-05-21 36 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); 
      } 
     } 
    }