美文网首页
c#反射获取属性

c#反射获取属性

作者: UnityAsk | 来源:发表于2016-12-27 11:34 被阅读169次

using System.Reflection;

      class Config
       {
            public string encoding { get; set; }
            public string plugins { get; set; }
       } 
       将hashtable的key值赋给实体类config. 
         Hashtable ht = new Hashtable();

        ht.Add("encoding", "utf8");
        ht.Add("plugins", "xxxx");
        Config config = new Config();
        PropertyInfo[] propertys = config.GetType().GetProperties();
        foreach (PropertyInfo property in propertys)
        {
            for (int i = 0; i < ht.Count; i++)
            {
                property.SetValue(config, ht[property.Name].ToString(), null);
            }
        }

 -----------------------------------------------------------------------------------

public class ForeachClass
{
/// <summary>
/// C#反射遍历对象属性
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="model">对象</param>
public static void ForeachClassProperties<T>(T model)
{
Type t = model.GetType();
PropertyInfo[] PropertyList = t.GetProperties();
foreach (PropertyInfo item in PropertyList)
{
string name = item.Name;
object value = item.GetValue(model, null);
}
}
}

相关文章

网友评论

      本文标题:c#反射获取属性

      本文链接:https://www.haomeiwen.com/subject/cjnsvttx.html