您的位置:首页 > 编程语言 > C#

C# 一些代码片段

2015-04-13 22:37 211 查看
1、获取集合里泛型类型的实例对象

List<T> list;

Type[] types = list.GetType().GetGenericArguments();

foreach(var type in types)
{
System.Activator.CreateInstance(type);
}

虽然是个数组,但是此处好像只有一个值,所以
object obj =System.Activator.CreateInstance(types.First());


  

//然后可以获取类的属性做一些操作
var properties = TypeDescriptor.GetProperties(obj);
for (var i = 0; i < properties.Count; i++)
{
var property = properties[i];

//如果字段有 [Display(Name = "手机")] 或 [DisplayName("姓名")] 特性,则优先显示DisplayName,如果都为空则显示字段名
var displayAttribute = property.Attributes[typeof(DisplayAttribute)] as DisplayAttribute;
string columnName = property.DisplayName == property.Name
? (displayAttribute == null ? property.Name : displayAttribute.Name)
: property.DisplayName;
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: