2012-04-23 11 views
6

का उपयोग कर डिफ़ॉल्ट कन्स्ट्रक्टर के बिना कस्टम विशेषता कैसे जोड़ूं यह प्रश्न this one से संबंधित है, लेकिन यह डुप्लिकेट नहीं है। जेबी कि एक कस्टम विशेषता जोड़ने के लिए वहां तैनात निम्नलिखित स्निपेट काम करेगा:मैं mono.cecil

ModuleDefinition module = ...; 
MethodDefinition targetMethod = ...; 
MethodReference attributeConstructor = module.Import(
    typeof(DebuggerHiddenAttribute).GetConstructor(Type.EmptyTypes)); 

targetMethod.CustomAttributes.Add(new CustomAttribute(attributeConstructor)); 
module.Write(...); 

मैं कुछ इसी तरह उपयोग करना चाहते हैं, लेकिन एक कस्टम विशेषता जिसका निर्माता अपनी (केवल) निर्माता में दो स्ट्रिंग पैरामीटर लेता है जोड़ने के लिए, और मैं उन लोगों के लिए मूल्य निर्दिष्ट करना चाहता हूं (जाहिर है)। क्या कोई मदद कर सकता है? स्ट्रिंग तर्क के साथ जिम्मेदार बताते हैं

MethodReference attributeConstructor = module.Import(
    typeof(MyAttribute).GetConstructor(new [] { typeof(string), typeof(string) })); 

तो फिर तुम बस कस्टम पॉप्युलेट कर सकते हैं::

उत्तर

12

सबसे पहले आप निर्माता के उचित संस्करण के लिए एक संदर्भ प्राप्त करने के लिए

CustomAttribute attribute = new CustomAttribute(attributeConstructor); 
attribute.ConstructorArguments.Add(
     new CustomAttributeArgument(
      module.TypeSystem.String, "Foo")); 
attribute.ConstructorArguments.Add(
     new CustomAttributeArgument(
      module.TypeSystem.String, "Bar")); 
+0

कभी जेबी के रूप में त्वरित - मदद के लिए बहुत बहुत धन्यवाद। मेरे जवाब को स्वीकार करने के लिए बहुत तेज़, जो मैं कुछ मिनटों में करूँगा ... –

+0

Google को रीयल-टाइम में एसई अनुक्रमणित करना होगा: मैं मोनो.सीसिल पर एक साधारण Google अलर्ट का उपयोग कर रहा हूं। –

+0

वाह - प्रभावशाली। –

2

यहाँ नाम सेट करने का तरीका एक कस्टम विशेषता के पैरामीटर जो इसके रचनाकारों का उपयोग करके एक विशेषता मान की सेटिंग को पूरी तरह से बाईपास करते हैं। एक नोट के रूप में आप CustomAttributeNamedArgument.Argument.Value या यहां तक ​​कि CustomAttributeNamedArgument.Argument को सीधे पढ़ा नहीं जा सकता है।

निम्नलिखित स्थापित करने के बराबर है - [XXX(SomeNamedProperty = {some value})]

var attribDefaultCtorRef = type.Module.Import(typeof(XXXAttribute).GetConstructor(Type.EmptyTypes)); 
    var attrib = new CustomAttribute(attribDefaultCtorRef); 
    var namedPropertyTypeRef = type.Module.Import(typeof(YYY)); 
    attrib.Properties.Add(new CustomAttributeNamedArgument("SomeNamedProperty", new CustomAttributeArgument(namedPropertyTypeRef, {some value}))); 
    method.CustomAttributes.Add(attrib);