2010-02-21 13 views
41

मैं प्रतिबिंब का उपयोग करके विशेषता वर्ग से कक्षा के गुणों तक पहुंच बनाना चाहता हूं। क्या यह संभव है?क्या सी # विशेषताएँ लक्ष्य कक्षा तक पहुंच सकते हैं?

उदाहरण के लिए:

class MyAttribute : Attribute 
{ 
    private void AccessTargetClass() 
    { 
     // Do some operations 
    } 
} 

[MyAttribute] 
class TargetClass 
{ 
} 

उत्तर

15
नहीं

सीधे, लेकिन आदेश विशेषता कुछ भी करने के लिए, आप पहले से ही टाइप/सदस्य के लिए एक संभाल और उसके GetCustomAttributes विधि कॉल है, तो आप बस इसे पारित कर सकते हैं चाहिए में वहाँ से:

class MyAttribute : Attribute 
{ 
    public void DoSomethingWithDeclaringType(Type t) 
    { 
    } 
} 

इतना है कि यह का उपयोग करना:

Type classType = typeof(MyClass); 
object[] attribs = classType.GetCustomAttributes(typeof(MyAttribute), true); 
if(attribs.Length > 0) 
{ 
    ((MyAttribute)attribs[0]).DoSomethingWithDeclaringType(classType); 
} 
+2

आप विशेषता प्रकार में घोषित करने का प्रकार भी प्रदान कर सकते हैं, जिससे आप उस प्रकार तक पहुंच सकते हैं। जैसे ' वर्ग MyAttribute: गुण { निजी शून्य MyAttribute (प्रकार declaringType) { // पहुँच यहाँ टाइप करें, यहाँ तक कि एक संदर्भ रखना अगर जरूरत की घोषणा। } } [MyAttribute (typeof (TargetClass))] वर्ग TargetClass { } ' – Jaans

18

वहाँ की गिरफ्तारी ई मामले जहां आप एक प्रकार के संदर्भ को पारित करने के लिए कॉलिंग कोड पर भरोसा नहीं कर सकते हैं।

नीचे एक समाधान है जिसे मैंने इस समस्या को हल करने के लिए पकाया है। यह एक शॉट गन दृष्टिकोण का एक सा है, लेकिन यह काम करता है ...

using System; 
using System.Reflection; 
using System.Collections.Generic; 
using System.Linq; 
using System.Diagnostics; 


namespace Ethica.Reflection 
{ 
    /// <summary> 
    /// Helps in discovery of the target of an Attribute 
    /// </summary> 
    /// <typeparam name="TAttribute">An Attribute derived type</typeparam> 
    /// <remarks> 
    /// The .NET framework does not provide navigation from attributes back to their targets, principally for the reason that 
    /// in typical usage scenarios for attributes, the attribute is discovered by a routine which already has a reference to a 
    /// member type. 
    /// 
    /// There are, however, bona-fide cases where an attribute needs to detect it's target - an example is a localizable sub-class of the 
    /// DescriptionAttribute. In order for the DescriptionAttribute to return a localized string, it requires a resource key and, ideally, 
    /// a type reference as the base-key for the ResourceManager. A DescriptionAttribute could not provide this information without 
    /// a reference to it's target type. 
    /// 
    /// Note to callers: 
    /// 
    /// Your Attribute-derived class must implement Equals and GetHashCode, otherwise a run-time exception will occur, since this class 
    /// creates a dictionary of attributes in order to speed up target lookups. 
    /// </remarks> 
    public static class AttributeTargetHelper<TAttribute> 
     where TAttribute : Attribute 
    { 
     /// <summary> 
     /// Map of attributes and their respective targets 
     /// </summary> 
     private static Dictionary<TAttribute, object> targetMap; 

     /// <summary> 
     /// List of assemblies that should not be rescanned for types. 
     /// </summary> 
     private static List<string> skipAssemblies; 

     /// <summary> 
     /// Adds an attribute and it's target to the dictionary 
     /// </summary> 
     /// <param name="attribute"></param> 
     /// <param name="item"></param> 
     private static void Add(TAttribute attribute, object item) 
     { 
      targetMap.Add(attribute, item); 
     } 

     /// <summary> 
     /// Scans an assembly for all instances of the attribute. 
     /// </summary> 
     /// <param name="assembly"></param> 
     private static void ScanAssembly(Assembly assembly) 
     { 
      const BindingFlags memberInfoBinding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance; 

      if (!skipAssemblies.Contains(assembly.FullName)) 
      { 
       skipAssemblies.Add(assembly.FullName); 

       Debug.WriteLine("Loading attribute targets for " + typeof(TAttribute).Name + " from assembly " + assembly.FullName); 

       foreach (TAttribute attr in assembly.GetCustomAttributes(typeof(TAttribute), false)) 
        Add(attr, assembly); 

       foreach (Type type in assembly.GetTypes()) 
       { 
        foreach (TAttribute attr in type.GetCustomAttributes(typeof(TAttribute), false)) 
         Add(attr, type); 

        foreach (MemberInfo member in type.GetMembers(memberInfoBinding)) 
        { 
         foreach (TAttribute attr in member.GetCustomAttributes(typeof(TAttribute), false)) 
          Add(attr, member); 

         if (member.MemberType == MemberTypes.Method) 
          foreach (var parameter in ((MethodInfo)member).GetParameters()) 
           foreach (TAttribute attr in parameter.GetCustomAttributes(typeof(TAttribute), false)) 
            Add(attr, parameter); 
        } 
       } 
      } 

      foreach (var assemblyName in assembly.GetReferencedAssemblies()) 
      { 
       if (!skipAssemblies.Contains(assemblyName.FullName)) 
        ScanAssembly(Assembly.Load(assemblyName)); 
      } 
     } 

     /// <summary> 
     /// Returns the target of an attribute. 
     /// </summary> 
     /// <param name="attribute">The attribute for which a target is sought</param> 
     /// <returns>The target of the attribute - either an Assembly, Type or MemberInfo instance.</returns> 
     public static object GetTarget(TAttribute attribute) 
     { 
      object result; 
      if (!targetMap.TryGetValue(attribute, out result)) 
      { 
       // Since types can be loaded at any time, recheck that all assemblies are included... 
       // Walk up the stack in a last-ditch effort to find instances of the attribute. 
       StackTrace stackTrace = new StackTrace();   // get call stack 
       StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames) 

       // write call stack method names 
       foreach (StackFrame stackFrame in stackFrames) 
       { 
        Console.WriteLine(stackFrame.GetMethod().Name); // write method name 
        ScanAssembly(stackFrame.GetMethod().GetType().Assembly); 
       } 

       if (!targetMap.TryGetValue(attribute, out result)) 
        throw new InvalidProgramException("Cannot find assembly referencing attribute"); 
      } 
      return result; 
     } 

     /// <summary> 
     /// Static constructor for type. 
     /// </summary> 
     static AttributeTargetHelper() 
     { 
      targetMap = new Dictionary<TAttribute, object>(); 

      // Do not load any assemblies reference by the assembly which declares the attribute, since they cannot possibly use the attribute 
      skipAssemblies = new List<string>(typeof(TAttribute).Assembly.GetReferencedAssemblies().Select(c => c.FullName)); 

      // Skip common system assemblies 
      skipAssemblies.Add("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); 
      skipAssemblies.Add("System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); 
      skipAssemblies.Add("System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); 
      skipAssemblies.Add("System.Data.SqlXml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); 
      skipAssemblies.Add("System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); 
      skipAssemblies.Add("System.Numerics, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); 

      // Scan the entire application 
      ScanAssembly(Assembly.GetEntryAssembly()); 
     } 

    } 


    /// <summary> 
    /// Extends attributes so that their targets can be discovered 
    /// </summary> 
    public static class AttributeTargetHelperExtension 
    { 
     /// <summary> 
     /// Gets the target of an attribute 
     /// </summary> 
     /// <typeparam name="TAttribute"></typeparam> 
     /// <param name="attribute">The attribute for which a target is sought</param> 
     /// <returns>The target of the attribute - either an Assembly, Type or MemberInfo instance.</returns> 
     public static object GetTarget<TAttribute>(this TAttribute attribute) 
      where TAttribute : Attribute 
     { 
      return AttributeTargetHelper<TAttribute>.GetTarget(attribute); 
     } 
    } 
} 
+0

समाधान के लिए धन्यवाद काम करता है के" DoSomethingWithDeclaringType "प्रकार जब तक इंतजार कर के दृष्टिकोण है, लेकिन यह किसी भी तरह कि लागू करने का मतलब है – Heka

12

गुण प्राथमिक उद्देश्य एनोटेशन है: आप यह घोषणा करते? उस वर्ग/विधि/संपत्ति का इस तरह या इस तरह से व्यवहार किया जाना चाहिए, लेकिन वह कोड जो वास्तव में उन सभी चीजों को समेकित करता है, किसी अन्य स्थान पर होना चाहिए। इसलिए विशेषता के अंदर कुछ करने का आपका इरादा इस पैटर्न को तोड़ रहा है। मेरी सलाह: एक और समाधान पर विचार करें।

+0

चेक केवल DoSomethingWithDeclaringType के पहले कॉल पर किया जाता है, और इसका मतलब यह सुनिश्चित करना है कि कोई भी विशेषता को सीधे देखता है और स्वीकृति फ़ंक्शन के बिना इसके साथ कुछ करता है। यदि मैं कर सकता था, तो मैं इस सत्यापन कोड को विशेषता में ही रखूंगा, और मुझे नहीं लगता कि यह संभव होने पर पैटर्न का उल्लंघन करेगा। – DMC

+0

मान लीजिए कि एक विशेषता एक वर्ग और दूसरे के बीच संबंध स्थापित कर रही है। आप सत्यापन कोड कहां कहते हैं, "हां, ये दो वर्ग वास्तव में एक दूसरे के साथ संगत हैं?" मैं लोड कोड पर एक बार उस कोड को चलाने के लिए चाहता हूं, जब विशेषता स्थापित हो, और मैं यह सुनिश्चित करने के लिए विशेषता को जोड़ता हूं कि वे प्रत्येक वर्ग पर भरोसा नहीं करना चाहते हैं ताकि वे कनेक्शन को मान्य करने के लिए कोड डाल सकें। "DoSomethingWithDeclaringType" प्रकार के काम तक प्रतीक्षा करने का दृष्टिकोण, लेकिन इसका मतलब है कि किसी भी तरह से यह लागू करना कि चेक केवल DoSomethingWithDeclaringTyp को पहले कॉल पर किया जाता है – DMC

संबंधित मुद्दे