C#,内部与思考 [英] c#, Internal, and Reflection

查看:149
本文介绍了C#,内部与思考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有通过反射来执行内部代码的方式

Is there a way to execute "internal" code via reflection?

下面是一个例子程序:

using System;
using System.Reflection;

namespace ReflectionInternalTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Assembly asm = Assembly.GetExecutingAssembly();

            // Call normally
            new TestClass();

            // Call with Reflection
            asm.CreateInstance("ReflectionInternalTest.TestClass", 
                false, 
                BindingFlags.Default | BindingFlags.CreateInstance, 
                null, 
                null, 
                null, 
                null);

            // Pause
            Console.ReadLine();
        }
    }

    class TestClass
    {
        internal TestClass()
        {
            Console.WriteLine("Test class instantiated");
        }
    }
}



创建TestClass的正常工作完美,但是当我尝试创建通过反射一个实例,我得到一个错误missingMethodException说,它不能找到构造函数(也就是,如果你试图从组件外部调用它会发生什么)。

Creating a testclass normally works perfectly, however when i try to create an instance via reflection, I get a missingMethodException error saying it can't find the Constructor (which is what would happen if you tried calling it from outside the assembly).

这是不可能的,或者是有一些解决办法,我可以做什么?

Is this impossible, or is there some workaround i can do?

推荐答案

根据Preets方向备用后:

Based on Preets direction to an alternate post:

using System;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace ReflectionInternalTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Assembly asm = Assembly.GetExecutingAssembly();

            // Call normally
            new TestClass(1234);

            // Call with Reflection
            asm.CreateInstance("ReflectionInternalTest.TestClass", 
                false, 
                BindingFlags.Default | BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.NonPublic, 
                null, 
                new Object[] {9876}, 
                null, 
                null);

            // Pause
            Console.ReadLine();
        }
    }

    class TestClass
    {
        internal TestClass(Int32 id)
        {
            Console.WriteLine("Test class instantiated with id: " + id);
        }
    }
}

这工作。 (由一个参数来证明它是一个新的实例)。

This works. (Added an argument to prove it was a new instance).

原来我只是需要实例和非公开的BindingFlags。

turns out i just needed the instance and nonpublic BindingFlags.

这篇关于C#,内部与思考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆