简体   繁体   中英

`this[object Key]` unlimited number of arguments

I want to make this[object key] take an unlimited number of arguments, how can I do this?

For example, I have a code -

public class Response
{
    public object this[object Key]
    {
        get
        {
            return "Hello";
        }
    }
}

public class Program
{
    static async Task Main(string[] args)
    {
        Response response = new Response();

        var test = response["fds"]; //I can do this
        var test2 = response["fds"]["dsa"]; //But this is how I cannot do
    }
}

How can I do as shown in test2 so that I can take an unlimited number of arguments?

If you return object than it has no such property. You have to cast it to some kind of object

public class Response : IResponse
{
    public object this[object Key]
    {
        get
        {
            return "Hello";
        }
    }
}
public interface IResponse
{
    object this[object Key] { get; }
}
public class Program
{
    static async Task Main(string[] args)
    {
        Response response = new Response();

        var test = response["fds"]; //I can do this
        var test2 = (response["fds"] as IResponse)?["dsa"]; //But response["fds"] have to be IResponse if it's not you will get null
    }
}

To match your syntax, you probably want to return dynamic rather than object (so you can write the second index invocation without ceremony). When you're returning something that is meant to allow deeper access, you'd return something Response -like:

public class Response
{
    public dynamic this[object Key]
    {
        get
        {
            if(Key is int)
            {
               return "Hello";
            }
            else
            {
                return new Response();
            }
        }
    }
}

You'll hopefully have a clearer idea of how these nested objects will relate together and so may not need to new up one, or it may be some other class that exposes a similar indexer as Response .

This line, using the above definition:

var test3 = response["fds"]["dsa"]["jkl"][5];

Should produce "Hello".

Since you mentioned JSON.Net, it's approach doesn't use dynamic - but it's JToken.Item indexer always returns an object of the same type - another JToken . That's how you might choose to solve it but you wouldn't be returning a plain "Hello" as an alternative any longer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM