how to get parameter name in c#?

mc 5,451 Reputation points
2023-01-30T05:50:44.7+00:00
        public string BuildParameter(object[] para)
        {
            var parameters = "";

            for (var i = 0; i < para.Length; i++)
            {
                if (para[i]  != null)
                {
                    parameters += "&" + nameof(para[i]) + "=" + para[i];
                }
            }
return parameters
}


but I can not use nameof(para[i]);

I do not know how many parameters I will concat so I use parameter object[] para

I may call this function like : `string parameter=BuildParameter(new object[]{PageIndex,Filter});

public int PageIndex{get;set;} public string Filter{get;set;}`

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | .NET | .NET Runtime
Developer technologies | .NET | Other
Developer technologies | .NET | .NET CLI
0 comments No comments
{count} votes

Accepted answer
  1. Rena Ni - MSFT 2,066 Reputation points
    2023-01-30T07:58:36.9333333+00:00

    Hi @打玻璃,

    I suggest you using dynamic instead of object[]. Here is a whole working demo you could follow:

    public string BuildParameter(dynamic para)
    {
        var parameters = "";
        IDictionary<string, object> propertyValues = (IDictionary<string, object>)para;
        foreach(var item in propertyValues)
        {
            if(item.Value!=null)
            {
                parameters+= "&" + item.Key + "=" + item.Value;
            }
        }
        return parameters;
    }
    

    You can call this function like:

    dynamic s = new ExpandoObject();  
    s.PageIndex = 1;  
    s.Filter = "aa";
    string parameter = BuildParameter(s);
    

    If there has any problem, please let me know freely.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,

    Rena

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.