反射_程序集_额外补充

本文详细探讨了.NET框架中的反射机制,包括如何使用反射动态操作类型、成员以及加载和解析程序集。同时,还提供了关于程序集的额外知识,帮助读者深化对.NET运行时的理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

反射_程序集_额外补充<18/9/2017>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;//反射需要引用命名空间
using System.Text;
using System.Threading.Tasks;

namespace 反射
{
    class Program
    {
        static void Main(string[] args)
        {
            Type t = Type.GetType("反射.Animal");
            Type t1 = typeof(Animal);
            Console.WriteLine(t.Equals(t1));//返回为true,返回对象是一样的


            ConstructorInfo info = t.GetConstructor(new Type[] { typeof(int), typeof(string) });
            object o = info.Invoke(new object[] { 1, "abc" });
            //上面两句代码等同于下面这行代码
            object o1 = Activator.CreateInstance(t, new object[] { 1, "adc" });
            //
            MethodInfo mi = t.GetMethod("Run");
            mi.Invoke(o1, null);


            MethodInfo mm = t.GetMethod("Sing");
            mm.Invoke(null, null);
            //1.静态方法可以传空执行,非静态方法必须有一个目标对象,如上
            //2.可以返回一个结果,如下
            MethodInfo mm1 = t.GetMethod("Sing2");
            object sss = mm1.Invoke(null,null);
            Console.WriteLine(sss);


            PropertyInfo[] pies= t.GetProperties();
            pies[0].SetValue(o1, 1001);
            Console.WriteLine(((Animal)o1).Id);
        }
    }

    public class Animal
    {
        public int Id { get; set; }    
        public int a;
        public string b;
        public Animal(int a,string b)
        {
            this.a = a;
            this.b = b;
        }
        public Animal()
        {

        }
        public void Run()
        {
            Console.WriteLine("123123213213");
        }
        public static void Sing()
        {
            Console.WriteLine("kkkkkkkkkkkk");
        }
        public static string Sing2()
        {
            return "xxxxxx";
        }
    }

    public class Cat : Animal
    {
        public int ba;
        public string bb;
        public Cat(int a,string b)
        {
            this.ba = a;
            this.bb = b;
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值