使用 C# 中的典型获取集属性.带参数

本文关键字:属性 参数 获取 典型 使用 | 更新日期: 2023-09-27 17:47:23

我想在 C# 中做同样的事情。是否可以像在此 VB.NET 示例中使用参数"Key"一样将 C# 中的属性与参数一起使用

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

谢谢

使用 C# 中的典型获取集属性.带参数

无论如何在 C# 中使用带有参数的属性

不。只能在 C# 中为默认属性提供参数,以对索引访问进行建模(如在字典中):

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

其他属性不能有参数。请改用函数。顺便说一下,在 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

在 C# 中执行此操作的"正确"方法是创建专门用于访问集合的子类。它应该保存集合本身或具有与父类的内部链接。

针对

您的问题,一个更通用、更安全且可重用的解决方案可能是实现一个泛型的"参数化"属性类,如下所示:

    // Generic, parameterized (indexed) "property" template
    public class Property<T>
    {
        // The internal property value
        private T PropVal = default(T);
        // The indexed property get/set accessor 
        //  (Property<T>[index] = newvalue; value = Property<T>[index];)
        public T this[object key]
        {
            get { return PropVal; }     // Get the value
            set { PropVal = value; }    // Set the value
        }
    }

然后,您可以在公共类中实现任意数量的属性,以便客户端可以使用索引、描述符、安全密钥或其他任何内容设置/获取属性,如下所示:

    public class ParameterizedProperties
    {
        // Parameterized properties
        private Property<int> m_IntProp = new Property<int>();
        private Property<string> m_StringProp = new Property<string>();
        // Parameterized int property accessor for client access
        //  (ex: ParameterizedProperties.PublicIntProp[index])
        public Property<int> PublicIntProp
        {
            get { return m_IntProp; }
        }
        // Parameterized string property accessor
        //  (ex: ParameterizedProperties.PublicStringProp[index])
        public Property<string> PublicStringProp
        {
            get { return m_StringProp; }
        }
    }

最后,客户端代码将访问公共类的"参数化"属性,如下所示:

        ParameterizedProperties parmProperties = new ParameterizedProperties();
        parmProperties.PublicIntProp[1] = 100;
        parmProperties.PublicStringProp[1] = "whatever";
        int ival = parmProperties.PublicIntProp[1];
        string strVal = parmProperties.PublicStringProp[1];

当然,这看起来很奇怪,但它绝对可以解决问题。 此外,从客户端代码的角度来看,它一点也不奇怪 - 它简单直观,就像真实属性一样。 它不会违反任何 C# 规则,也不会与其他 .NET 托管语言不兼容。 从类实现者的角度来看,创建一个可重用的、泛型的、"参数化"的属性模板类会使组件编码变得相对轻而易举,如此处所示。

注意:您始终可以重写泛型属性类以提供自定义处理,例如索引查找、安全控制的属性访问或您想要的任何内容。

干杯!

马克·琼斯

下面是一个示例(根据 Grauenwolf 的建议进行了更改):

using System;
using System.Collections.Generic;
public class Test
{
    public FakeIndexedPropertyInCSharp DictionaryElement { get; set; }
    public Test()
    {
        DictionaryElement = new FakeIndexedPropertyInCSharp();
    }
    public class FakeIndexedPropertyInCSharp
    {
        private Dictionary<string, object> m_Dictionary = new Dictionary<string, object>();
        public object this[string index]
        {
            get 
            {
                object result;
                return m_Dictionary.TryGetValue(index, out result) ? result : null;
            }
            set 
            {
                m_Dictionary[index] = value; 
            }
        }
    }

}
class Program
{
    static void Main(string[] args)
    {
        Test t = new Test();
        t.DictionaryElement["hello"] = "world";
        Console.WriteLine(t.DictionaryElement["hello"]);
    }
}

你的代码示例让我感到非常奇怪的设计,并且滥用了属性的用途。为什么不只是实例方法AddOrUpdateKey

Public Sub AddOrUpdateKey(ByVal Key As String, ByVal Value as Object)
    If m_Dictionary.ContainsKey(Key) Then
        m_Dictionary(Key) = Value
    Else
        m_Dictionary.Add(Key, Value)
    End If
End Sub

如果密钥不存在,您的属性也会返回String.Empty,但声明返回Object,也不返回String

谢谢康拉德、艾伦、格劳恩沃尔夫、

总之,我不能像在 VB.NET 中那样使用 C# 属性...... :_( 无论如何,你的回答对我来说非常有用,我可能会把这个想法带到我的 C# 代码中。

除了属性问题的答案外,还有其他优点。例如

  • 使用TryGetValue,它更快。查询字典两次。
  • 资源库不必测试该值是否已存在。

也感谢 Sören,使用一种方法不太符合我最初的目标,但非常感谢。