CustomReflectionContext Class (System.Reflection.Context)

Cambia visualizzazione:
ScriptFree
.NET Framework Class Library
CustomReflectionContext Class

[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]

Represents a customizable reflection context.

Inheritance Hierarchy

System.Object
  System.Reflection.ReflectionContext
    System.Reflection.Context.CustomReflectionContext
      System.ComponentModel.Composition.Registration.RegistrationBuilder

Namespace:  System.Reflection.Context
Assembly:  System.Reflection.Context (in System.Reflection.Context.dll)
Syntax

Visual Basic

Public MustInherit Class CustomReflectionContext _
	Inherits ReflectionContext
C#

public abstract class CustomReflectionContext : ReflectionContext
Visual C++

public ref class CustomReflectionContext abstract : public ReflectionContext
F#

[<AbstractClass>]
type CustomReflectionContext =  
    class
        inherit ReflectionContext
    end

The CustomReflectionContext type exposes the following members.

Constructors

  Name Description
Protected method CustomReflectionContext() Initializes a new instance of the CustomReflectionContext class.
Protected method CustomReflectionContext(ReflectionContext) Initializes a new instance of the CustomReflectionContext class with the specified reflection context as a base.
Top
Methods

  Name Description
Protected method AddProperties When overridden in a derived class, provides a collection of additional properties for the specified type, as represented in this reflection context.
Protected method CreateProperty(Type, String, Func<Object, Object>, Action<Object, Object>) Creates an object that represents a property to be added to a type, to be used with the AddProperties(Type) method.
Protected method CreateProperty(Type, String, Func<Object, Object>, Action<Object, Object>, IEnumerable<Attribute>, IEnumerable<Attribute>, IEnumerable<Attribute>) Creates an object that represents a property to be added to a type, to be used with the AddProperties(Type) method and using the specified custom attributes.
Public method Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Protected method GetCustomAttributes(MemberInfo, IEnumerable<Object>) When overridden in a derived class, provides a list of custom attributes for the specified member, as represented in this reflection context.
Protected method GetCustomAttributes(ParameterInfo, IEnumerable<Object>) When overridden in a derived class, provides a list of custom attributes for the specified parameter, as represented in this reflection context.
Public method GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Public method GetTypeForObject Gets the representation of the type of the specified object in this reflection context. (Inherited from ReflectionContext.)
Public method MapAssembly Gets the representation, in this reflection context, of an assembly that is represented by an object from another reflection context. (Overrides ReflectionContext.MapAssembly(Assembly).)
Public method MapType Gets the representation, in this reflection context, of a type represented by an object from another reflection context. (Overrides ReflectionContext.MapType(TypeInfo).)
Protected method MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method ToString Returns a string that represents the current object. (Inherited from Object.)
Top
Remarks

CustomReflectionContext provides a way for you to add or remove custom attributes from reflection objects, or add dummy properties to those objects, without re-implementing the complete reflection model. The default CustomReflectionContext simply wraps reflection objects without making any changes, but by subclassing and overriding the relevant methods, you can add, remove, or change the attributes that apply to any reflected parameter or member, or add new properties to a reflected type.

For example, suppose that your code follows the convention of applying a particular attribute to factory methods, but you are now required to work with third-party code that lacks attributes. You can use CustomReflectionContext to specify a rule for identifying the objects that should have attributes and to supply the objects with those attributes when they are viewed from your code.

To use CustomReflectionContext effectively, the code that uses the reflected objects must support the notion of specifying a reflection context, instead of assuming that all reflected objects are associated with the runtime reflection context. Many reflection methods in the .NET Framework provide a ReflectionContext parameter for this purpose.

To modify the attributes that are applied to a reflected parameter or member, override the GetCustomAttributes(ParameterInfo, IEnumerable<Object>) or GetCustomAttributes method. These methods take the reflected object and the list of attributes under its current reflection context, and return the list of attributes it should have under the custom reflection context.

Caution note Caution

CustomReflectionContext methods should not access the list of attributes of a reflected object or method directly by calling the GetCustomAttributes method on the provided MemberInfo or ParameterInfo instance, but should instead use the declaredAttributes list, which is passed as a parameter to the GetCustomAttributes method overloads.

To add properties to a reflected type, override the AddProperties method. The method accepts a parameter that specifies the reflected type, and returns a list of additional properties. You should use the CreateProperty method to create property objects to return. You can specify delegates when creating the property that will serve as the property accessor, and you can omit one of the accessors to create a read-only or write-only property. Note that such dummy properties have no metadata or Common Intermediate Language (CIL) backing.

Caution note Caution

Be cautious about equality among reflected objects when you work with reflection contexts, because objects may represent the same reflected object in multiple contexts. You can use the MapType method to obtain a particular reflection context's version of a reflected object.

Caution note Caution

A CustomReflectionContext object alters the attributes returned by a particular reflection object, such as those obtained by the GetCustomAttributes method. It does not alter the custom attribute data returned by the GetCustomAttributesData method, and these two lists will not match when you use a custom reflection context.

Examples

The following example demonstrates how to subclass CustomReflectionContext to add a custom attribute to all the members of a given type whose names begin with "To". To run this code, paste it into an empty console project, and make sure to include a reference to System.Reflection.Context.dll.

C#

//A blank example attribute.
class myAttribute : Attribute
{


}

//Reflection context with custom rules.
class myCRC : CustomReflectionContext
{
    //Called whenever the reflection context checks for custom attributes.
           protected override IEnumerable<object> GetCustomAttributes(MemberInfo member, IEnumerable<object> declaredAttributes)
           {   
               //Add example attribute to "To*" members.
               if (member.Name.StartsWith("To")) {
                   yield return new myAttribute();
               }
               //Keep existing attributes as well.
               foreach (var attr in declaredAttributes) yield return attr;
         }    
}


class Program
{
    static void Main(string[] args)
    {
        myCRC mc = new myCRC();
        Type t = typeof(String);

        //A representation of the type in the default reflection context.
        TypeInfo ti = t.GetTypeInfo();

        //A representation of the type in the customized reflection context.
        TypeInfo myTI = mc.MapType(ti);

        //Display all the members of the type and their attributes.
        foreach (MemberInfo m in myTI.DeclaredMembers)
        {
           Console.WriteLine(m.Name + ":");
           foreach (Attribute cd in m.GetCustomAttributes()) 
           {
                Console.WriteLine(cd.GetType());
           }

        }

        Console.WriteLine();

        //The "ToString" member as represented in the default reflection context.
        MemberInfo mi1 = ti.GetDeclaredMethods("ToString").FirstOrDefault();

        //All the attributes of "ToString" in the default reflection context.
        Console.WriteLine("'ToString' Attributes in Default Reflection Context:");
        foreach (Attribute cd in mi1.GetCustomAttributes())
        {
            Console.WriteLine(cd.GetType());
        }

        Console.WriteLine();

        //The same member in the custom reflection context.
        mi1 = myTI.GetDeclaredMethods("ToString").FirstOrDefault();

        //All its attributes, for comparison.  myAttribute is now included.
        Console.WriteLine("'ToString' Attributes in Custom Reflection Context:");
        foreach (Attribute cd in mi1.GetCustomAttributes())
        {
            Console.WriteLine(cd.GetType());
        }

        Console.ReadLine();
    }
}


Version Information

.NET Framework

Supported in: 4.5
Platforms

Windows 8 Release Preview, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 SP2, Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
See Also

Reference