自定义使用索引器[]

Gav*_*vin 8 c# asp.net

我想创建一个与ASP.Net Session类似的对象.

假设我将此对象称为mySession,我想在你做的时候这样做

mySession["Username"] = "Gav"
Run Code Online (Sandbox Code Playgroud)

如果它不存在,它将把它添加到数据库表中,如果存在则更新它.我可以编写一个方法来执行此操作但不知道如何在使用索引器语法([])时触发它.我从来没有用索引器构建一个做这样的事情的对象.

在任何人说任何事情之前,我知道ASP.Net会话可以保存到数据库,但在这种情况下,我需要一个稍微简单的自定义解决方案.

以这种方式使用索引器的任何指针或示例都会很棒.

谢谢

Rex*_*x M 20

它实际上与编写典型属性几乎相同:

public class MySessionThing
{
    public object this[string key]
    {
        //called when we ask for something = mySession["value"]
        get
        {
            return MyGetData(key);
        }
        //called when we assign mySession["value"] = something
        set
        {
            MySetData(key, value);
        }
    }

    private object MyGetData(string key)
    {
        //lookup and return object
    }

    private void MySetData(string key, object value)
    {
        //store the key/object pair to your repository
    }
}
Run Code Online (Sandbox Code Playgroud)

唯一的区别是我们使用关键字"this"而不是给它一个正确的名称:

public          object            MyProperty
^access         ^(return) type    ^name
 modifier

public          object            this
^ditto          ^ditto            ^ "name"
Run Code Online (Sandbox Code Playgroud)


Dan*_*den 6

MSDN文档:

class SampleCollection<T>
{
    // Declare an array to store the data elements.
    private T[] arr = new T[100];

    // Define the indexer, which will allow client code
    // to use [] notation on the class instance itself.
    // (See line 2 of code in Main below.)        
    public T this[int i]
    {
        get
        {
            // This indexer is very simple, and just returns or sets
            // the corresponding element from the internal array.
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }
}

// This class shows how client code uses the indexer.
class Program
{
    static void Main(string[] args)
    {
        // Declare an instance of the SampleCollection type.
        SampleCollection<string> stringCollection = new SampleCollection<string>();

        // Use [] notation on the type.
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}
Run Code Online (Sandbox Code Playgroud)