我希望能够:
- 检查对象是否定义了索引运算符。
- 如果它被定义,我希望能够使用它。
我想在下面的代码中实现这一点。该代码包含一个对象 (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