代码
/// <summary>
/// 获取类的所有属性
/// </summary>
/// <param name="IsLower">是否所有属性名称均为小写</param>
/// <returns>返回属性名称数组</returns>
public static string[] ToArray(this object source, bool IsLower = true)
{
if (source == null) return new string[] { };
List<string> arraylist = new List<string>();
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
{
if (IsLower)
{
arraylist.Add(property.Name.ToLower());
}
else
{
arraylist.Add(property.Name);
}
}
return arraylist.ToArray();
}
/// <summary>
/// 类所有属性转化成带分隔符的字符串
/// </summary>
/// <param name="source">类</param>
/// <param name="IsLower">是否小写</param>
/// <param name="Segmenter">分割符</param>
/// <returns>返回字符串</returns>
public static string ToStringJoin(this object source, bool IsLower = true, char Segmenter = ',')
{
var str = source.ToArray(IsLower);
return string.Join(Segmenter, str);
}
调用
class Program
{
static void Main(string[] args)
{
var Moel = new Model() { A=3,B=3,C=3};
var res = Moel.ToStringJoin();
Console.WriteLine(res);
Console.ReadKey();
}
}
public class Model
{
public int A { get; set; }
public int B { get; set; }
public int C { get; set; }
public string DD { get; set; }
}
结果