111,130
社区成员
发帖
与我相关
我的任务
分享
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;
}
}
}
}
}
Type MyType = Type.GetType("Myproperty"); //定义MyType获取Myproperty的类型Type MyType = Type.GetType("PropertyInfo类.Myproperty"); //定义MyType获取Myproperty的类型Type MyType = typeof(Myproperty); //Type.GetType("Myproperty"); //定义MyType获取Myproperty的类型