c# - 检查索引运算符是否存在

标签 c# multidimensional-array

我希望能够:

  • 检查对象是否定义了索引运算符。
  • 如果已定义,我希望能够使用它。

我想在下面的代码中实现它。 该代码包含一个对象 (MyObject),该对象提供一种遍历多维数组或哈希表链接集的方法。如果请求路径中的节点不存在,它也应该防止给出错误。 我想不通的部分是代码中的注释部分:

public class MyObject
{
    private object myObject = null;

    public MyObject()
    {
    }

    public MyObject(object value)
    {
        myObject = value;
    }

    public void setValue(object value)
    {
        myObject = value;
    }

    public object getValue()
    {
        return myObject;
    }

    public object this[string key]
    {
        get
        {
            if (myObject == null) 
            {
                return new MyObject(null);
            }
            else
            {
                // determine what of type/class myObject is and if it has indexing operators defined
                // if defined, access them and return the result
                // else return null.
            }
        }
        set
        {
            if (myObject == null)
            {
                // do nothing (or throw an exception);
            }
            else{
                // determine what of type/class myObject is
                // determine if that type/class has indexing operators defined
                // if defined, access them and set the result there
                // else do nothing (or throw an exception).
            }
        }
    }
}

这是我想要完成的:

        // given these variables:
        string loremIpsumString = "lorem ipsum dolor sit amet";
        int[] digits = new int[10];
        for (int i = 0; i <= 3; i++) digits[i] = i;
        Hashtable outerHashtable = new Hashtable();
        Hashtable innerHashtable = new Hashtable();
        innerHashtable.Add("contents", "this is inside");
        outerHashtable.Add("outside", "this is outside");
        outerHashtable.Add("inside", innerHashtable);

        // I can already print this:
        Response.Write(    loremIpsumString    ); // prints "lorem ipsum dolor sit amet"
        Response.Write(    digits[0]    ); // prints "0"
        Response.Write(    digits[1]    ); // prints "1"
        Response.Write(    digits[2]    ); // prints "2"
        Response.Write(    outerHashtable["outside"]    ); // prints "this is outside"
        Response.Write(    ((Hashtable)outerHashtable["inside"])["contents"]    ); // prints "this is outside"

        // But I want to be to do it this way:
        MyObject myObject;

        myObject = new MyObject(loremIpsumString);
        Response.Write(    myObject.getValue()    ); // prints "lorem ipsum dolor sit amet"
        Response.Write(    myObject["unexistant"].getValue()    ); // prints nothing/null
        myObject = new MyObject(digits);
        Response.Write(    myObject[0].getValue()    ); // prints "0"
        Response.Write(    myObject[1].getValue()    ); // prints "1"
        Response.Write(    myObject[2].getValue()    ); // prints "2"
        myObject = new MyObject(outerHashtable);
        Response.Write(    myObject["outside"].getValue()    ); // prints "this is outside"
        Response.Write(    myObject["inside"]["contents"].getValue()    ); // prints "this is inside"
        Response.Write(    myObject["unexistant"].getValue()    ); // prints nothing/null
        Response.Write(    myObject["unexistant"]["unexistant"]["unexistant"].getValue()    ); // prints nothing/null

最佳答案

您可以先检查它是否继承了 IList 以涵盖(通用的)Lists 和 Arrays。如果没有,您可以使用 PropertyInfo.GetIndexParameters检查它是否有索引器:

get
{
    if (myObject == null)
    {
        return null;
    }
    else
    {
        // not sure which index(es) you want
        int index = 0;
        Type t = myObject.GetType();
        if (typeof(IList).IsAssignableFrom(t))
        {
            IList ilist = (IList)myObject;
            return ilist[index];
        }
        else
        {
            var indexer = t.GetProperties()
                .Where(p => p.GetIndexParameters().Length != 0)
                .FirstOrDefault();
            if (indexer != null)
            {
                object[] indexArgs = { index };
                return indexer.GetValue(myObject, indexArgs);
            }
            else
                return null;
        }
    }
}

DEMO (使用一个 string,它有一个 indexer 来访问字符)

关于c# - 检查索引运算符是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14462820/

相关文章:

c# - 使用类名作为方法参数和返回类型

c# 当子 pictureBox 更改 Image 时调整父控件的大小

c# - 在 ASP.NET Identity Core 中,我可以更改 UserToken 主键吗

c# - 如果 asp :Panel generate a div, 什么生成跨度?

c - 传递一个二维结构数组

c# - 使用什么访问修饰符

javascript - 替换数组中的值

java - java中的bin二维数组

python - Python 中稀疏矩阵的矩阵乘法

c# - 多维数组枚举器是否保证所有实现的顺序相同?