gpt4 book ai didi

c# - 在 C# 中使用典型的 get set 属性...带参数

转载 作者:太空狗 更新时间:2023-10-29 17:31:55 25 4
gpt4 key购买 nike

我想在 C# 中做同样的事情。无论如何,在 C# 中使用带有参数的属性,就像我在这个 VB.NET 示例中使用参数“Key”一样吗?

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

谢谢

最佳答案

Is there anyway of using properties in C# with parameters

没有。您只能在 C# 中为 default 属性提供一个参数,以模拟索引访问(如在字典中):

public T this[string key] {
get { return m_Dictionary[key]; }
set { m_Dictionary[key] = value; }
}

其他属性不能有参数。请改用函数。顺便说一句,建议在 VB 中执行相同的操作,以便其他 .NET 语言(C# …)可以使用您的代码。

顺便说一下,您的代码不必要地复杂。四件事:

  • 您不需要对 String 标识符进行转义。直接使用关键字。
  • 为什么不使用 ""
  • 使用TryGetValue,速度更快。你查询字典两次。
  • 您的 setter 不必测试该值是否已经存在。

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

关于c# - 在 C# 中使用典型的 get set 属性...带参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/236530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com