CSDN广告是越来越多了,所有博客笔记不再更新,新网址 DotNet笔记
遍历一个类/或类对象的属性/值,很有用,看个例子
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication13
{
class Program
{
static void Main(string[] args)
{
//新建一个对象
Object o = new {name="zhifeiya",@class="myclass" };
//如果有name这个属性
if(JudgeHasProperty("name",o))
{
//输出name的值
Console.WriteLine(GetPropertyValueByName("name",o).ToString());
}
//遍历该ae对象的name/value (这是一个系统类,这里拿来测试一下)
ApplicationException ae = new ApplicationException();
ForeachPropertyValues(ae);
Console.Read();
}
/// <summary>
/// 判断 对象 中是否有该属性(不区分大小写)
/// </summary>
/// <param name="PropertyName">属性名称</param>
/// <param name="o">目标对象</param>
/// <returns></returns>
public static bool JudgeHasProperty(string PropertyName,Object o)
{
if (o == null)
{
o = new { };
}
PropertyInfo[] p1 = o.GetType().GetProperties();
bool b = false;
foreach (PropertyInfo pi in p1)
{
if (pi.Name.ToLower() == PropertyName.ToLower())
{
b = true;
}
}
return b;
}
/// <summary>
/// 获取指定属性的值(不区分大小写)
/// </summary>
/// <param name="PropertyName">属性名称</param>
/// <param name="o">目标对象</param>
/// <returns></returns>
public static Object GetPropertyValueByName(string PropertyName, Object o)
{
if (o == null)
{
o = new { };
}
//创建一个返回对象
Object returnObject=new Object();
PropertyInfo[] p1 = o.GetType().GetProperties();
foreach (PropertyInfo pi in p1)
{
if (pi.Name.ToLower() == PropertyName.ToLower())
{
returnObject = pi.GetValue(o);
}
}
return returnObject;
}
/// <summary>
/// 遍历属性的名称/值(显示形式:name=value)
/// </summary>
/// <param name="o"></param>
public static void ForeachPropertyValues( Object o)
{
if (o == null)
{
o = new { };
}
PropertyInfo[] p1 = o.GetType().GetProperties();
foreach (PropertyInfo pi in p1)
{
Console.WriteLine(pi.Name + ":" + pi.GetValue(o,null));
}
}
}
}
运行结果:
场景案例:比如想对HtmlHelper写一个扩展的生成Button标签的方法:
public static MvcHtmlString MyButton(this HtmlHelper h, Object HtmlAttribute)
{
if (HtmlAttribute == null)
{
HtmlAttribute = new { };
}
string str = "";
PropertyInfo[] p1 = HtmlAttribute.GetType().GetProperties();
foreach (PropertyInfo pi in p1)
{
str += " " + pi.Name + "='" + pi.GetValue(HtmlAttribute, null).ToString() + "' ";
}
return new MvcHtmlString( "<input type='button' " + str + " >");
}
使用的时候,在视图中,我们就可以这样直接调用了:
@Html.MyButton(new { id="but",name="butname",@class="myclass",value="submit"})
生成的html代码:
<input type='button' id='but' name='butname' class='myclass' value='submit' >