在C#中使用反射调用internal的方法

MSDN上解释Internal如下:

The internal keyword is an access modifier for types and type members. Internal types or members are accessible only within files in the same assembly.

即, 仅允许相同程序集内的代码调用类型或成员.

那么是否可以调用这些internal的方法呢?

如果被调用的程序集, 在代码中使用了InternalsVisibleToAttribute来标示一个或多个友元程序集, 那么这些被标为友元的程序集就可以访问被调用程序集的internal方法. 下例是程序集A的代码, 它宣布AssemblyB为友元程序集

// This file is for Assembly A.

using System.Runtime.CompilerServices;
using System;

[assembly: InternalsVisibleTo("AssemblyB")]

// The class is internal by default.
class FriendClass
{
    public void Test()
    {
        Console.WriteLine("Sample Class");
    }
}

// Public class that has an internal method.
public class ClassWithFriendMethod
{
    internal void Test()
    {
        Console.WriteLine("Sample Method");
    }

}

更具体的一行代码示例如下:

[assembly: InternalsVisibleTo("AssemblyB, PublicKey=32ab4ba45e0a69a1")]

那么如果我们要调用的是第三方人写的代码里的internal的方法, 怎么办呢?

答案是使用反射.

下面是被调用的类的源代码.

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

namespace internalclasstest
{
    public class PubClass
    {
        public void Speak()
        {
            Console.WriteLine("PubClass speaks: You are so nice!");
        }

        //Internal method
        internal void Mock()
        {
            Console.WriteLine("PubClass mocks: You suck!");
        }
    }

    //Internal class
    class InternalClass
    {
        public void Speak()
        {
            Console.WriteLine("InternalClass speaks: I love my job!");
        }

        void Moci()
        {
            Console.WriteLine("InternalClass speaks: I love Friday night!");
        }
    }
}

下面是使用反射并调用PubClass的Internal 函数Mock的代码示例:

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

namespace reflectionInternal
{
    class Program
    {
        static void Main(string[] args)
        {
            Assembly asm = Assembly.LoadFile(@"E:\internalclasstest\bin\Debug\internalclasstest.dll");
            Type t1 = asm.GetType("internalclasstest.PubClass");

            ConstructorInfo t1Constructor = t1.GetConstructor(Type.EmptyTypes);
            Object oPubClass = t1Constructor.Invoke(new Object[] { });

            MethodInfo oMethod = t1.GetMethod("Mock", BindingFlags.Instance | BindingFlags.NonPublic);
            oMethod.Invoke(oPubClass, new Object[]{});
        }
    }
}
时间: 2024-08-04 14:13:30

在C#中使用反射调用internal的方法的相关文章

根据类名,方法名,反射调用类的方法

/** * 根据类名,方法名,反射调用类的方法 * @方法名称: getResult * @描述: TODO * @param className * @param methodName * @param params * @return */ public static String getResult(String className,String methodName,Map<String,Object> params){ String result = null; try{ Objec

C#通过反射调用类及方法

反射有个典型的应用,就是菜单的动态加载,原理就是通过反射调用某个窗体(类).下面演示一下通过反射调用类及方法: 1.新建一个类,命名为:ReflectionHelper,代码如下: #region 创建对象实例 /// <summary> /// 创建对象实例 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="assemblyN

C#中Winform动态调用Webservice的方法(转)

一般情况下winform调用webservice时步骤 1添加服务引用---高级----添加web引用------填写url--添加web引用即可完成对webservice的引用 让VS.NET环境来为我们生成服务代理,然后调用对应的Web服务. 如果需要动态调用WebService,要实现这样的功能: publicstaticobjectInvokeWebService(stringurl,  stringmethodname,object[] args) 其中,url是Web服务的地址,me

java 通过反射调用属性,方法,构造器

package reflection2; import static org.junit.Assert.assertArrayEquals; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.junit.jupiter

ASP.NET4.0中JavaScript脚本调用Web Service 方法

环境:VS2019  .net 4.0 framework 根据教材使用ScriptManager在JavaScript中调用Web service 时,失败.现将过程和解决方法记录如下: 1.定义Web Service using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; namespace AjaxTest1 { /// <

java简单反射调用get,set方法

public Object setDate(ResultSet rs,Object o) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IntrospectionException, IllegalArgumentException, InvocationTargetException, SQLException{ Class cs = Class.forName(o.getClass

在C++中反射调用.NET(二)

反射调用返回复杂对象的.NET方法 定义数据接口 上一篇在C++中反射调用.NET(一)中,我们简单的介绍了如何使用C++/CLI并且初步使用了反射调用.NET程序集的简单方法,今天我们看看如何在C++与.NET程序集之间传递复杂对象. 先看看.NET程序集的一个返回对象的方法: public IUserInfo GetUserByID(int userId) { IUserInfo userinfo= EntityBuilder.CreateEntity<IUserInfo>(); user

反射工具类(调用父类的方法和字段)

使用这个工具类,可以完成父类,基类,方法,字段,无论什么权限都可以调用. package com.reflect; /** * 基类 * @author jianghui */ public class GrandParent { public String publicField = "1"; String defaultField = "2"; protected String protectedField = "3"; private St

LuaInterface的反射调用机制研究

一直不明白LuaInterface和lua之间反射调用的原理,花了两天时间读了一下代码,稍微总结了一下 附上所用LuaInterface的地址,可以用git直接clone https://github.com/fengxiaorui/luainterface 下面进入正题: 先说说两个关键的载入函数,也是进行反射调用的基础: 1.LoadAssembly 在Lua调用load_assembly后会被调用,目的是载入某个程序集到程序集缓存中 通过代码可以发现这里只是通过栈上传入的字符串加载对应的程