how to get parameter name in c#?

mc 4,596 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;}`

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,918 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,611 questions
.NET CLI
.NET CLI
A cross-platform toolchain for developing, building, running, and publishing .NET applications.
337 questions
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,166 questions
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.