首页 > 技术文章 > c# 反射列子

mengluo 2016-07-26 09:43 原文

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            Assembly nc = Assembly.LoadFile(Environment.CurrentDirectory + "\\PersonOperator.dll");

            Type t = nc.GetType("PersonOperator.Person",true);

            object o = Activator.CreateInstance(t, new object[] { "你", 20 });

            FieldInfo f = t.GetField("name");
            f.SetValue(o, "奥特你们");

            PropertyInfo p = t.GetProperty("Name");
            p.SetValue(o, "你哈", null);

            MethodInfo m = t.GetMethod("Play", new Type[] { });
            m.Invoke(o, null);


            MethodInfo m1 = t.GetMethod("Play", new Type[] { typeof(string),typeof(string) });
            m1.Invoke(o, new object[]{"低价傲人","你好"});


            Console.ReadKey();
           


       




            
            

        }
    }
}

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PersonOperator
{
  public  class Person
    {
      public string name;
      public int age;
      public string gender;


      public string Name
      {
          get { return name; }
          set { name = value; }
      }
      public int Age
      {
          get { return age; }
          set { age = value; }
      }
      public string Gender
      {
          get { return gender; }
          set { gender = value; }
      }

      public Person(string _name,int _age)
      {
          name = _name;
          age = _age;
      }

      public void Play()
      {
          Console.WriteLine(name+"去打篮球");
      }
      public void Play(string name2,string name3)
      {
          Console.WriteLine(name + "和"+name2+"去打篮球"+name3+"奥特曼");
      }
    }
}

  

推荐阅读