2012-10-17 2 views
1

Mono.Cecil을 사용하여 메서드에 사용자 지정 특성을 추가하려고합니다. 사용자 지정 특성의 생성자는 System.Type입니다. Mono.Cecil을 사용하여 이러한 사용자 지정 특성을 만드는 방법과 System.Type 매개 변수에 대한 인수가 무엇인지 알아 내려고합니다. 지금까지 해봤Type을 인수로 사용하는 사용자 지정 특성을 추가하는 방법

public class SampleAttribute : Attribute { 
    public SampleAttribute (Type type) {} 
} 

:

내 속성은 다음과 같이 정의된다

var module = ...; 
var method = ...; 
var sampleAttributeCtor = ...; 

var attribute = new CustomAttribute (sampleAttributeCtor); 

attribute.ConstructorArguments.Add (
    new ConstructorArgument (module.TypeSystem.String, module.GetType ("TestType").FullName)); 

을하지만 작동하지 않습니다. 어떤 생각?

var module=targetExe.MainModule; 
      var anothermodule=sampleDll.MainModule; 
      var custatt = new CustomAttribute(ctorReference); 


      var corlib =module .AssemblyResolver.Resolve((AssemblyNameReference)module.TypeSystem.Corlib); 
      var systemTypeRef = module.Import(corlib.MainModule .GetType("System.Type")); 
      custatt.ConstructorArguments.Add(new CustomAttributeArgument(systemTypeRef, module.Import(anothermodule.GetType("SampleDll.Annotation")))); 
      methodDef.CustomAttributes.Add(custatt); 

어떤 제안을 다음과 같이

나는 코드를 업데이트 한?

+0

나는 Mono.Cecil 질문에 답해도 괜찮지 만, 읽기 쉽도록 도와 주어야합니다. 제시된 코드는 색이 잘 잡히지 않고 지저분한 것이며, 몇 줄로 줄여서 질문에 대한 생각을 할 수 있습니다. 이 질문을 편집하여 예제를 제공 할 것입니다. –

답변

2

사용자 지정 특성의 형식이 문자열로 전체 이름을 사용하여 인코딩되는 경우에도 Cecil은이를 추상화합니다.

Mono.Cecil의 Type 표현은 TypeReference (또는 형식이 동일한 모듈에서 온 경우 TypeDefinition)입니다.

그냥 인수로 전달하면됩니다. 먼저 사용자 지정 특성 인수의 형식으로 사용할 System.Type 형식에 대한 참조를 가져와야합니다. 유형은 당신이 쓸 수있는 인자로 사용하려는 위치에 따라

var corlib = module.AssemblyResolver.Resolve ((AssemblyNameReference) module.TypeSystem.Corlib); 
var systemTypeRef = module.Import (corlib.GetType ("System.Type")); 

: 그리고

attribute.ConstructorArguments.Add (
    new ConstructorArgument (
     systemTypeRef, 
     module.GetType ("TestType"))); 

또는 관심있는 유형이 다른 모듈에있는 경우, 당신이 가져올 필요

참조 :

attribute.ConstructorArguments.Add (
    new ConstructorArgument (
     systemTypeRef, 
     module.Import (anotherModule.GetType ("TestType")))); 
+0

안녕하세요, 귀하의 솔루션을 시도하고 "작업의 현재 상태로 인해 유효하지 않은 오류가 발생했습니다." –

+0

var custatt = 새 CustomAttribute (ctorReference); var corlib = inputmodule.AssemblyResolver.Resolve (inputmodule.TypeSystem.Corlib.Name); var systemTypeRef = inputmodule.Import (corlib.GetType()); custatt.ConstructorArguments.Add (새 CustomAttributeArgument (systemTypeRef, inputmodule.Import (anothermodule .GetType ("SampleDll.Annotation"))))); methodDef.CustomAttributes.Add (custatt); –

+0

@ MururganAlagesan 아니야. systemTypeRef를 초기화하는 값은 내가 작성한 값이 아닙니다. –