简体   繁体   中英

How to create a method that takes any object and returns a name:value pair for all properties?

For example I have a simple class like

public class Person{ 
    public int Age {get;set;}
    public string Name {get;set;}
}

I need to make a method that takes any class and spits out values of properties set in the object as a string in format "Age:35;Name:John Doe;"

I am looking for a method signature on the lines of

public string SpitNameValuePairs<T>() 

or something like it. How can this be done efficiently if using reflection?

Here is a quick implementation.

    public static string SplitNameValuePairs(object value)
    {
        string retVal = string.Empty;
        List<string> keyValuePairs = new List<string>();

        foreach (var propInfo in value.GetType().GetProperties())
        {
            keyValuePairs.Add(string.Format("{0}:{1};", propInfo.Name, propInfo.GetValue(value, null).ToString()));
        }

        retVal = string.Join("", keyValuePairs.ToArray());

        return retVal;
    }

Then called like this:

        var person = new Person();
        person.Name = "Hello";
        person.Age = 10;
        Console.WriteLine(SplitNameValuePairs(person));

That have protection from crashes when property have an indexer defined and also it output only instance properties (no static).

    private static string SplitNameValuePairs<T>(T value)
    {
        StringBuilder sb = new StringBuilder();

        foreach (PropertyInfo property in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
        {
            if (property.GetIndexParameters().Length == 0)
                sb.AppendFormat("{0}:{1};", property.Name, property.GetValue(value, null));
        }
        return sb.ToString();
    }

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