首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

反射遇到的小疑点,高手来看看

2012-02-09 
反射遇到的小问题,高手来看看!C# code%@ Page LanguageC# %script runatserverpublic void Page

反射遇到的小问题,高手来看看!

C# code
<%@ Page Language="C#" %><script runat="server">    public void Page_Load(object sender, EventArgs e)    {        System.Collections.Generic.List<string> source = new System.Collections.Generic.List<string> { "A", "B", "C", "D", "E" };        foreach (object data in source)        {            Type type = data.GetType();            foreach (System.Reflection.PropertyInfo property in type.GetProperties())            {                object propertyValue = property.GetValue(data, null);                string value = (propertyValue == null) ? string.Empty : propertyValue.ToString();                Response.Write(property.Name + " = " + value + ",");            }            Response.Write("<br />");        }    }</script>


asp.net的,麻烦您运行下,
会报: 参数计数不匹配。
……
异常详细信息: System.Reflection.TargetParameterCountException: 参数计数不匹配。
到发帖为止有那么点明白了,但还是不很清楚为什么会出现这样的异常!?

[解决办法]
.Net跟C#不一样
C#里有属性和索引的概念,但是.Net里统称为属性
所以你调用GetProperties方法会检索到索引,即:
string s="Hello";
s[i]//会检索到该索引
显然,索引是有参数的,而你统一用:
property.GetValue(data, null);
你用null表示没有参数,于是会提示参数计数不匹配
[解决办法]
因为string里面有个属性是chars
这个需要index参数的
你可以参考下http://msdn.microsoft.com/en-us/library/b05d59ty.aspx

热点排行