using System.Reflection.PropertyInfo类较熟悉,帮我看个例题.

sageking2 2009-01-11 08:55:06

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace PropertyInfo类
{
class MyPropertyInfo
{
static void Main(string[] args)
{
Console.WriteLine("\nReflection.PropertyInfo");
Myproperty Myproperty = new Myproperty(); //实例化一个对象并且把类名覆盖了
Type MyType = Type.GetType("Myproperty"); //定义MyType获取Myproperty的类型
PropertyInfo MyPropertyInfo = MyType.GetProperty("Caption"); //报错:要实例化
Console.Write("\nGetValue= " + MyPropertyInfo.GetValue(Myproperty,null));

MyPropertyInfo.SetValue(Myproperty,"This caption has been changed",null);
Console.Write("\n"+MyType.FullName+"."+MyPropertyInfo.Name +" has a PropertyType of "+MyPropertyInfo.PropertyType);
Console.Write("\nGetValue - "+MyPropertyInfo.GetValue(Myproperty,null));

MethodInfo Mygetmethodinfo = MyPropertyInfo.GetSetMethod();
Console.Write("\nSetAccessor for "+ MyPropertyInfo.Name+" returns a "+Mygetmethodinfo.ReturnType);
Console.Write("\n\n"+MyType.FullName+"."+MyPropertyInfo.Name+" GetSetMethod - "+MyPropertyInfo.GetSetMethod());

Console.Read();
}
}

public class Myproperty
{
private string caption = "A Default caption";
public string Caption
{
get
{
return caption;
}
set
{
if (caption != value)
{
caption = value;
}
}
}
}

}

因为这个例题的命名比较变态,报错居然是缺少实例化,难道是我漏了某行?我真的找不出哪错了.
...全文
629 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
lalac 2009-01-11
  • 打赏
  • 举报
回复
这一句有问题:
Type MyType = Type.GetType("Myproperty"); //定义MyType获取Myproperty的类型

这里GetType传入参数指的是type名,需要的是全名,就是[namespace].[typename]的样子。
lz可以这样改:
Type MyType = Type.GetType("PropertyInfo类.Myproperty"); //定义MyType获取Myproperty的类型

或者
Type MyType = typeof(Myproperty); //Type.GetType("Myproperty"); //定义MyType获取Myproperty的类型

sageking2 2009-01-11
  • 打赏
  • 举报
回复
Thank$!

111,131

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧