使用C#进行字符串索引 [英] string indexing using C#

查看:145
本文介绍了使用C#进行字符串索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个集合类来存储我的业务对象的集合.内部的业务对象与关联键一起存储在Dictionary中.

我想知道是否有一种方法可以向集合类中添加属性,以便可以通过键引用对象.例如MyClass.MyObject ["Key"].

I am writing a collection class to store a collection of my business objects. Th business objects internally are stored in a Dictionary with an associate key.

I am wondering if there is a way to add a property to my collection class so that I can reference my objects by a key. For example MyClass.MyObject["Key"].

推荐答案

是的,当然,只有示例中显示的语法不正确,通常不正确,而不仅仅是与索引.它必须像这样工作:

Yes of course, only you show incorrect syntax in your example, generally incorrect, not just in relation to the indexing. It must work like this:

MyClass myInstance = new MyClass( /*...*/ );
//...
myInstance.SomeInstanceMethod( /*...*/ );
MyClass.SomeStaticMethod( /*...*/ );
var propertyValue = myInstance.SomeInstanceProperty;
var staticPropertyValue = MyClass.SomeStaticProperty;

//likewise, with indexing:
var myIndexingValue = myInstance["string index"];
//no static equivalent, unlike regular scalar property...



它是使用所谓的索引器(使用关键字this)来实现的.它们可以是只读,只写和读/写,与常规的标量属性完全一样(setter或getter可以具有单独的访问说明符):



It is implemented using so called indexer, using key word this. They can be read-only, write-only and read/write, exactly like regular scalar properties (setters or getters can have separate access specifiers):

class MyClass {
    //in this example, type of indexed property is int, 
    //type of index is string;
    //these two can be any two types:
    public int this[string index] {
        get { return Dictionary[index]; }
        set { Dictionary[index] = value; }
    } //this
    //...
    System.Collections.Generic.Dictionary<string, int> Dictionary =
        new System.Collections.Generic.Dictionary<string, int>();
} //myClass



重要的是要注意:索引属性只能是实例一,不能是静态.

现在,这是上述示例的通用变体:



It''s important to note: indexed property can only be the instance one, it cannot be static.

Now, here is the generic variant of the above sample:

class MyClass<THIS_TYPE, INDEX_TYPE> {
    public THIS_TYPE this[INDEX_TYPE index] {
        get { return Dictionary[index]; }
        set { Dictionary[index] = value; }
    } //this
    System.Collections.Generic.Dictionary<INDEX_TYPE, THIS_TYPE> Dictionary =
        new System.Collections.Generic.Dictionary<INDEX_TYPE, THIS_TYPE>();
} //myClass



现在的问题是:如何使一个类具有多个具有不同索引类型的索引属性?无法直接执行.唯一的方法是用不同类型的索引属性实现一个或多个接口.您可以在我对此问题的回答之一中找到一个示例:
数组中引用对象的位置? [ ^ ].请查看类NeuralNetwork的示例实现.

—SA



Now, the problem is: how to make a class having more than one indexed property of different index types? It''s not possible to do it directly. The only way is to implement one or more interfaces with different types of indexed properties. You can find one example in one of my asnwers to this question:
Location of a refernced object in an array?[^]. Please look at the sample implementation of the class NeuralNetwork.

—SA


您的两个选项是:

-创建一个属性以公开字典:
Your two options are:

-Create a property to expose the dictionary:
public Dictionary<string, object> MyObject { get; private set; }



-对MyClass类使用索引器来访问字典:



-Use an indexer for the MyClass class to access the dictionary:

public object this[string key]
{
  get
  {
    return this.dictionary[key];
  }
}


您可以使用Dictionary来实现此功能.但是,在实施时应谨慎.这是因为字典索引不是线程安全的.有关更多信息,请参见为什么字典索引器不是线程安全的,以及如何使它 [ ^ ]

下面,我写了一种实现此功能的方法.

You can implement this functionality using Dictionary. However there should be caution when implementing it. This is because dictionary indexing is not thread safe. For more see Why Dictionary indexer is not thread safe and how to make it[^]

Below, I wrote one way of implementing this functionality.

/// <summary>
/// Base Indexer class
/// </summary>
/// <typeparam name="T">Any Type T</typeparam>
/// <typeparam name="E">Any Type E</typeparam>
public class BaseIndexer<T, E>
{
    /// <summary>
    /// Internal dictionary
    /// </summary>
    internal static IDictionary<T, E> dictionary = new Dictionary<T, E>();

    /// <summary>
    /// Add value to the dictionary
    /// </summary>
    /// <param name="key">Dictionary  <typeparamref name="T"/> Key</param>
    /// <param name="value">Dictionary <typeparamref name="E"/> value</param>
    public void Add(T key, E value)
    {
        if (!dictionary.ContainsKey(key)) // Make sure to check key,
            dictionary.Add(key, value);
        else
            throw new Exception("Key is not available.");
    }

    /// <summary>
    /// Get Type E object
    /// </summary>
    /// <param name="key">Key value</param>
    /// <returns>Type E object</returns>
    public E this[T key]
    {
        get
        {
            if (dictionary.ContainsKey(key))
                return dictionary[key];
            else
                throw new KeyNotFoundException();
        }
    }
}

/// <summary>
/// Employee business class
/// </summary>
public class Employee
{
    /// <summary>
    /// Get or set FirstName
    /// </summary>
    public string FirstName { get; set; }
    /// <summary>
    /// Get or set LastName
    /// </summary>
    public string LastName { get; set; }

    /// <summary>
    /// Employee business class
    /// </summary>
    public Employee()
    {
    }
}

/// <summary>
/// Employee Collection class
/// </summary>
public class Employees : BaseIndexer<string, Employee> {

    /// <summary>
    /// Employee Collection class
    /// </summary>
    public Employees()
    {
    }
}


private void button1_Click(object sender, EventArgs e)
{
    Employee emp1 = new Employee() {FirstName="Wonde", LastName="Tadesse" };
    Employee emp2 = new Employee() { FirstName = "John", LastName = "Doe" };
    Employees employees = new Employees();

    employees.Add(emp1.FirstName, emp1);
    employees.Add(emp2.LastName, emp2);

    textBox1.Text = employees[emp1.FirstName].LastName;
}


希望对您有帮助.


I hope this helps you well.


这篇关于使用C#进行字符串索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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