.NET의 반사를 사용하여 인터페이스를 생성합니다
-
02-07-2019 - |
문제
기존 인터페이스와 동일한 멤버와 동일한 멤버와 함께 런타임에 새 인터페이스를 생성해야합니다. 일부 메소드에 다른 속성을 배치한다는 점을 제외하고 (일부 속성 매개 변수는 런타임까지 알려져 있지 않습니다). 어떻게 달성 할 수 있습니까?
해결책
귀하의 질문은 그다지 구체적이지 않습니다. 더 많은 정보로 업데이트하면 추가 세부 사항 으로이 답을 살펴 보겠습니다.
다음은 관련된 수동 단계에 대한 개요입니다.
- 정의 된 동일 방지가있는 어셈블리를 만듭니다
- 정의 된 동체 모드로 모듈을 만듭니다
- DefineType으로 유형을 만듭니다. 확실히 통과하십시오
TypeAttributes.Interface
유형을 인터페이스로 만들려면 - 원래 인터페이스의 멤버를 반복하고 새로운 인터페이스에서 유사한 메소드를 구축하여 필요에 따라 속성을 적용하십시오.
- 부르다
TypeBuilder.CreateType
인터페이스 구축을 완료합니다.
다른 팁
속성이있는 인터페이스로 어셈블리를 동적으로 생성하려면 다음과 같습니다.
using System.Reflection;
using System.Reflection.Emit;
// Need the output the assembly to a specific directory
string outputdir = "F:\\tmp\\";
string fname = "Hello.World.dll";
// Define the assembly name
AssemblyName bAssemblyName = new AssemblyName();
bAssemblyName.Name = "Hello.World";
bAssemblyName.Version = new system.Version(1,2,3,4);
// Define the new assembly and module
AssemblyBuilder bAssembly = System.AppDomain.CurrentDomain.DefineDynamicAssembly(bAssemblyName, AssemblyBuilderAccess.Save, outputdir);
ModuleBuilder bModule = bAssembly.DefineDynamicModule(fname, true);
TypeBuilder tInterface = bModule.DefineType("IFoo", TypeAttributes.Interface | TypeAttributes.Public);
ConstructorInfo con = typeof(FunAttribute).GetConstructor(new Type[] { typeof(string) });
CustomAttributeBuilder cab = new CustomAttributeBuilder(con, new object[] { "Hello" });
tInterface.SetCustomAttribute(cab);
Type tInt = tInterface.CreateType();
bAssembly.Save(fname);
다음을 만듭니다.
namespace Hello.World
{
[Fun("Hello")]
public interface IFoo
{}
}
메소드 추가 typeBuilder.DefinemEthod를 호출하여 MethodBuilder 클래스를 사용하십시오.
제휴하지 않습니다 StackOverflow