문제

반사를 통해 "내부"코드를 실행하는 방법이 있습니까?

다음은 예제 프로그램입니다.

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");
        }
    }
}

테스트 클래스 만들기는 일반적으로 완벽하게 작동하지만 반사를 통해 인스턴스를 만들려고 할 때 생성자를 찾을 수 없다는 MissedMethodexception 오류가 발생합니다 (어셈블리 외부에서 호출하려고하면 발생하는 일).

이것이 불가능합니까, 아니면 내가 할 수있는 해결 방법이 있습니까?

도움이 되었습니까?

해결책 2

대체 게시물에 대한 preets 방향을 기준으로합니다.

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);
        }
    }
}

이것은 작동합니다. (새로운 사례임을 증명하기 위해 주장을 추가했습니다).

인스턴스와 비공개 바인딩 플래그가 필요했습니다.

다른 팁

여기 예입니다 ...

  class Program
    {
        static void Main(string[] args)
        {
            var tr = typeof(TestReflection);

            var ctr = tr.GetConstructor( 
                BindingFlags.NonPublic | 
                BindingFlags.Instance,
                null, new Type[0], null);

            var obj = ctr.Invoke(null);

            ((TestReflection)obj).DoThatThang();

            Console.ReadLine();
        }
    }

    class TestReflection
    {
        internal TestReflection( )
        {

        }

        public void DoThatThang()
        {
            Console.WriteLine("Done!") ;
        }
    }

C# 4.0 인 경우 AccessPrivateWrapper Dynamic Wrapper를 사용하십시오. http://amazedsaint.blogspot.com/2010/05/accessprivatewrapper-c-40-dynamic.html

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top