C# 反射

本文通过C#代码示例介绍了如何使用反射加载程序集并显示公共类型,以及如何使用泛型创建和实例化特定类型的字典。示例展示了如何通过MakeGenericType方法将开放泛型类型转换为封闭泛型类型,并使用Activator创建实例。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;


namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string dataAssembly = "System.Data,version =4.0.0.0,culture = neutral,PublicKeyToken=b77a5c561934e089";
            LoadAssemAndShowPublicTypes(dataAssembly);

            Console.Read();


        }

        private static void LoadAssemAndShowPublicTypes(string dataAssembly)
        {
            Assembly a = Assembly.Load(dataAssembly);

            foreach (Type t in a.ExportedTypes)
            {
                Console.WriteLine(t.FullName + Environment.NewLine);
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Runtime.InteropServices;

namespace ConsoleApp1
{

    internal sealed class Dictionary<TKey, TValue>
    {
        public TKey Key { get; set; }
        public TValue Value { get; set; }
        public Dictionary(TKey k, TValue v)
        {
            Key = k;
            Value = v;
        }

        public override string ToString()
        {
            return $"Key :{Key} Value:{Value}";
        }
    }

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

            Type openType = typeof(Dictionary<,>);
            Type closedType = openType.MakeGenericType(typeof(String), typeof(Int32));
            Object o = Activator.CreateInstance(closedType,"xxxxx",2);
            Console.WriteLine(o.ToString());
            Console.Read();
 
        }

    }
     
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值