Unity C# Basic Review 13 - Indexer (P288-290)

Indexer:

[Access modifier] Return value type this[any data type index] { set { } get { } }

Essence: Variations of methods

Function: Access method from object.Method name (parameter) => object [parameter]

Custom indexer VS array indexer

(1) The index value (Index) type of the indexer is not restricted

(2) Indexers allow reloading

(3) The indexer is not a variable

Indexers VS Properties

(1) Attributes are represented by names, and indexers are identified by functions.

(2) Indexers can be overloaded, but attributes cannot

(3) Indexers cannot be declared static, but attributes can be

public class Student 
{
    //索引器
    //indexer
    //["name"]["age"]
    public object this[string proName]
    {
        get
        {
            if (proName == "name")
            {
                return this.name;
            }
            if (proName == "age")
            {
                return this.age;
            }
            return null;
        }
        set
        {
            //"name" "age" value
            if (proName == "name")
            {
                this.name = value as string;
            }
            if (proName == "age")
            {
                this.age = (int)value;
            }
        }
    }
}
public class Program : MonoBehaviour
{
    void Start()
    {
        Student s = new Student();
        //s.Name = "校花";
        //Debug.Log(s.Name);

        //索引器的方式
        s["name"] = "校花";
        Debug.Log(s["name"]);
    }
}

Guess you like

Origin blog.csdn.net/weixin_46711336/article/details/123050652