在C#中使用典型的获取设置的属性...带参数 [英] Using the typical get set properties in C#... with parameters

查看:263
本文介绍了在C#中使用典型的获取设置的属性...带参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做同样的在C#。反正是有以同样的方式,我在这VB.NET例子参数'键'做使用C#与性能参数?




 专用共享m_Dictionary作为IDictionary的(字符串,对象)=新词典(字符串,对象)




 公共共享属性DictionaryElement(BYVAL主要作为字符串)作为对象
得到
。如果m_Dictionary.ContainsKey(键)和
返回m_Dictionary(密钥)
,否则
返回[字符串] .Empty
端如果
端获取
组(BYVAL值作为对象)
如果m_Dictionary.ContainsKey(键)和
m_Dictionary(密钥)=价值
,否则
m_Dictionary.Add(键,值)
端如果

端设置
高端物业

感谢


解决方案

反正在C#中使用属性与参数的




没有。您只可以提供的默认的属性在C#中有一个参数,模型索引访问(如在一个字典):

 公共牛逼此[字符串键] {
{返回m_Dictionary [关键] }
集合{m_Dictionary [关键] =价值; }
}

其他属性不能有参数。使用函数。顺便说一句,它的recommented做同样在VB使其他.NET语言(C#...)可以使用你的代码。



顺便说一句,你的代码是不必要的复杂。四件事情:




  • 您不必逃避字符串标识符。直接使用关键字。

  • 为什么不使用

  • 使用 TryGetValue ,它的速度更快。您查询字典的两倍。

  • 您的制定者不具备测试值是否已经存在。




 公共共享属性DictionaryElement(BYVAL主要作为字符串)作为对象
得到
尺寸沤作为字符串
如果m_Dictionary.TryGetValue(密钥,RET)然后返回RET
返回,'同的String.Empty! '
端获取
组(BYVAL值作为对象)
m_Dictionary(密钥)=价值
端设置
高端物业


I'd like to do the same in C#. Is there anyway of using properties in C# with parameters in the same way I've done with the parameter 'Key' in this VB.NET example?

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

Thanks

解决方案

Is there anyway of using properties in C# with parameters

No. You only can provide the default property in C# with an argument, to model indexed access (as in a dictionary):

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

Other properties can't have arguments. Use a function instead. By the way, it's recommented to do the same in VB so other .NET languages (C# …) can use your code.

By the way, your code is unnecessarily complicated. Four things:

  • You don't need to escape the String identifier. Use the keyword directly.
  • Why not use ""?
  • Use TryGetValue, it's faster. You query the dictionary twice.
  • Your setter doesn't have to test whether the value already exists.


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#中使用典型的获取设置的属性...带参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆