[英]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;" 我需要制作一个方法,该方法可以接受任何类,并以字符串形式“ 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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.