// get the assembly given the path name, and get the main module
var assembly = AssemblyDefinition.ReadAssembly(path);
var module = assembly.MainModule;
// Foo is the class that will get the attribute
var foo = module.Types.First(x => x.Name == "Foo");
// Import the DataContractAttribute and get it's default constructor
var attType =
module.Import(typeof(System.Runtime.Serialization.DataContractAttribute));
var attCtor = attType.Resolve().Methods.First(x => x.Name == ".ctor"
&& x.Parameters.Count == 0);
// Create a new attribute and decorate Foo with it
var custatt = new CustomAttribute(attCtor);
foo.CustomAttributes.Add(custatt);
// At this point, a save results in the following CustomAttribute
error (from IL Disassembler):
// .custom <invalid token 0x06000032> = (01 00 00 00) ...
/* However, suppose I have Bar alread decorated with the
DataContractAttribute, as in:
[DataContract]
public class Bar { }
* I can actually get the constructor from this attribute and
successully apply it to Foo, as follows:
*/
var bar = module.Types.First(x => x.Name == "Bar");
var custatt2 = new
CustomAttribute(bar.CustomAttributes[0].Constructor);
foo.CustomAttributes.Add(custatt2);
Any Idea how I can get the first scenario to work correctly? I'm
using .Net 4.0 (and I've compiled Mono.Cecil under 4.0 as well).
Would that make a difference?
--
--
mono-cecil