c# 反射调用方法及属性总结

ClassLibrary1.dll内容

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

namespace ClassLibrary1
{
   
    public class Class1
    {
   

        public int Number {
    get; set; } = 11;
         string Str {
    get; set
C#中的反射是一个强大的机制,允许程序在运行时检查程序集、模块和类型的信息,也可以动态创建类型的实例、绑定类型成员、获取和设置属性等。反射调用静态类的方法涉及以下几个步骤: 1. 获取到静态类的类型信息:首先需要获取到静态类的`Type`对象,可以通过`typeof(类名)`来获取。 2. 获取静态方法信息:通过`Type`对象调用`GetMethod`或者`GetMethods`方法来获取具体的静态方法信息。`GetMethod`用于获取指定名称的单个方法,`GetMethods`用于获取所有公开的静态方法。 3. 调用静态方法:使用`Invoke`方法来执行获取到的静态方法。`Invoke`方法的第一个参数是静态方法所在的类,由于是静态方法,因此可以传递`null`或者`Activator.CreateInstance(type)`来创建类的实例。 以下是一个简单的示例代码: ```csharp using System; using System.Reflection; public class Program { public static void Main() { // 获取静态类的类型信息 Type staticClassType = typeof(StaticClass); // 获取静态方法的信息,假设方法名为 "StaticMethod" MethodInfo staticMethodInfo = staticClassType.GetMethod("StaticMethod"); // 调用静态方法 object result = staticMethodInfo.Invoke(null, null); // StaticMethod 是静态方法,第一个参数为 null Console.WriteLine(result); } } public static class StaticClass { public static void StaticMethod() { Console.WriteLine("静态方法调用。"); } } ``` 在上面的示例中,`StaticClass`是一个静态类,它有一个静态方法`StaticMethod`。程序首先获取`StaticClass`的类型信息,然后获取`StaticMethod`方法的信息,并通过反射调用方法
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值