Jav*_*ier 9 c# vb.net properties
我想在C#中做同样的事情.有没有在C#中使用参数的属性,就像我在这个VB.NET示例中使用参数'Key'一样?
Run Code Online (Sandbox Code Playgroud)Private Shared m_Dictionary As IDictionary(Of String, Object) = New Dictionary(Of String, Object)
Public Shared Property DictionaryElement(ByVal Key As String) As Object
Get
If m_Dictionary.ContainsKey(Key) Then
Return m_Dictionary(Key)
Else
Return [String].Empty
End If
End Get
Set(ByVal value As Object)
If m_Dictionary.ContainsKey(Key) Then
m_Dictionary(Key) = value
Else
m_Dictionary.Add(Key, value)
End If
End Set
End Property
Run Code Online (Sandbox Code Playgroud)
谢谢
Kon*_*lph 14
无论如何在C#中使用带参数的属性
不可以.您只能在C#中使用参数提供默认属性,以建模索引访问(如在字典中):
public T this[string key] {
get { return m_Dictionary[key]; }
set { m_Dictionary[key] = value; }
}
Run Code Online (Sandbox Code Playgroud)
其他属性不能有参数.请改用功能.顺便说一句,它建议在VB中执行相同操作,以便其他.NET语言(C#...)可以使用您的代码.
顺便说一句,您的代码不必要地复杂化.四件事:
String标识符.直接使用关键字.""?TryGetValue,它更快.您查询字典两次.Public Shared Property DictionaryElement(ByVal Key As String) As Object
Get
Dim ret As String
If m_Dictionary.TryGetValue(Key, ret) Then Return ret
Return "" ' Same as String.Empty! '
End Get
Set(ByVal value As Object)
m_Dictionary(Key) = value
End Set
End Property
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37682 次 |
| 最近记录: |