C# `此[对象键]`参数数量不限

C# `此[对象键]`参数数量不限,c#,this,C#,This,我想让这个[object key]接受无限数量的参数,我怎么做 例如,我有一个代码- public class Response { public object this[object Key] { get { return "Hello"; } } } public class Program { static async Task Main(string[] args) {

我想让
这个[object key]
接受无限数量的参数,我怎么做

例如,我有一个代码-

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
    }
}

如何按照
test2
中所示执行,以便可以接受无限数量的参数?

如果返回的对象没有此类属性,则返回该对象。你必须把它投射到某种物体上

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
    }
}

为了匹配您的语法,您可能希望返回
dynamic
,而不是
object
(这样您就可以不用客气地编写第二个索引调用)。当您返回一些允许更深入访问的内容时,您会返回一些
Response
-例如:

public class Response
{
    public dynamic this[object Key]
    {
        get
        {
            if(Key is int)
            {
               return "Hello";
            }
            else
            {
                return new Response();
            }
        }
    }
}
希望您能够更清楚地了解这些嵌套对象将如何关联在一起,因此可能不需要
new
创建一个,也可能是其他类公开了与
Response
类似的索引器

该行使用上述定义:

var test3 = response["fds"]["dsa"]["jkl"][5];
应该产生“你好”


由于您提到了JSON.Net,它的方法不使用
动态
——但它的索引器总是返回相同类型的对象——另一个
JToken
。这就是您可能选择解决它的方式,但您不再返回一个简单的
“Hello”
作为替代。

这将要求此
返回的任何内容都有自己的索引器,而不是索引器支持多个参数,按照您显示的语法。您想要一个索引器(
response[“fds”,“dsa”];
)还是让返回的对象拥有自己的索引器?
var test3=JObject.Parse(response.ToString())[“fd”][“fdhgfd”]var test3=JObject.Parse(Response.ToString())[“fd”][“fdhgfd”]
,但我从未找到答案,现在处于一个小的stuporJObject中。Parse返回
JObject
JToken
),您可以通过索引
项[Object]
获取属性,请参阅