次の方法で共有


ReflectionPermission クラス

System.Reflection API 経由のメタデータへのアクセスを制御します。このクラスは継承できません。

この型のすべてのメンバの一覧については、ReflectionPermission メンバ を参照してください。

System.Object
   System.Security.CodeAccessPermission
      System.Security.Permissions.ReflectionPermission

<Serializable>
NotInheritable Public Class ReflectionPermission   Inherits CodeAccessPermission   Implements IUnrestrictedPermission
[C#]
[Serializable]
public sealed class ReflectionPermission : CodeAccessPermission,   IUnrestrictedPermission
[C++]
[Serializable]
public __gc __sealed class ReflectionPermission : public   CodeAccessPermission, IUnrestrictedPermission
[JScript]
public
   Serializable
class ReflectionPermission extends CodeAccessPermission   implements IUnrestrictedPermission

スレッドセーフ

この型の public static (Visual Basicでは Shared) のすべてのメンバは、マルチスレッド操作で安全に使用できます。インスタンスのメンバの場合は、スレッドセーフであるとは限りません。

解説

TypeSystem.Reflection 機能のルートです。 ReflectionPermission を使用しないと、コードは読み込まれたアセンブリの public メンバにしかアクセスできません。実際には、 Object.GetType への無制限アクセス、エクスポートされた public 型への Type.GetType を使用したアクセス、 GetTypeFromHandle へのアクセスなどができます。 FullName および Attributes など、 Type のプロパティの中には、 ReflectionPermission を使用せずにアクセスできるものもあります。

適切な ReflectionPermission を使用しているコードは、読み込まれた Typepublic メンバ、 protected メンバ、 private メンバにアクセスできます。つまり、 ModuleAssemblyBaseTypeGetInterfaces などにアクセスできます。

注意    ReflectionPermission を使用するとプライベートなクラス メンバやメタデータにアクセスできるため、インターネット コードには ReflectionPermission を使用しないようにしてください。

使用例

 
' This sample demonstrates the IsSubsetOf, Union, Intersect, Copy, ToXml and FromXml methods 
' of the ReflectionPermission class.
Imports System
Imports System.Security
Imports System.Security.Permissions
Imports Microsoft.VisualBasic

<Assembly: CLSCompliant(True)> 

Public Class ReflectionPermissionDemo

    ' IsSubsetOf determines whether the current permission is a subset of the specified permission.
    Private Function IsSubsetOfDemo() As Boolean
        Dim returnValue As Boolean = True
        Dim reflection1, reflection2 As ReflectionPermissionFlag
        Dim reflectionPerm1, reflectionPerm2 As ReflectionPermission
        Dim reflectionGen1 As New ReflectionGenerator()
        Dim reflectionGen2 As New ReflectionGenerator()
        reflectionGen1.ResetIndex()
        While reflectionGen1.CreateReflection(reflectionPerm1, reflection1)
            If reflectionPerm1 Is Nothing Then
                GoTo ContinueWhile1
            End If
            reflectionGen2.ResetIndex()
            Console.WriteLine("********************************************************" & ControlChars.Lf)

            While reflectionGen2.CreateReflection(reflectionPerm2, reflection2)
                If reflectionPerm2 Is Nothing Then
                    GoTo ContinueWhile2
                End If
                Try
                    If reflectionPerm1.IsSubsetOf(reflectionPerm2) Then
                        Console.WriteLine((reflectionPerm1.Flags.ToString() & " is a subset of " _
                        & reflectionPerm2.Flags.ToString()))
                    Else
                        Console.WriteLine((reflectionPerm1.Flags.ToString() & " is not a subset of " _
                        & reflectionPerm2.Flags.ToString()))
                    End If
                Catch e As Exception
                    Console.WriteLine(("An exception was thrown for subset :" & reflectionPerm1.ToString() _
                    & ControlChars.Lf & reflectionPerm2.ToString() & ControlChars.Lf & e.ToString()))
                    returnValue = False
                End Try
ContinueWhile2:
            End While
ContinueWhile1:
        End While
        Return returnValue
    End Function 'IsSubsetOfDemo

    ' Union creates a new permission that is the union of the current permission and the specified permission.
    Private Function UnionDemo() As Boolean
        Dim returnValue As Boolean = True
        Dim reflection1, reflection2 As ReflectionPermissionFlag
        Dim reflectionPerm1, reflectionPerm2 As ReflectionPermission
        Dim reflectionPerm3 As IPermission
        Dim reflectionGen1 As New ReflectionGenerator()
        Dim reflectionGen2 As New ReflectionGenerator()
        reflectionGen1.ResetIndex()
        While reflectionGen1.CreateReflection(reflectionPerm1, reflection1)
            If reflectionPerm1 Is Nothing Then
                GoTo ContinueWhile1
            End If
            Console.WriteLine("**********************************************************" & ControlChars.Lf)
            reflectionGen2.ResetIndex()

            While reflectionGen2.CreateReflection(reflectionPerm2, reflection2)
                If reflectionPerm2 Is Nothing Then
                    GoTo ContinueWhile2
                End If
                reflectionPerm3 = CType(reflectionPerm1.Union(reflectionPerm2), ReflectionPermission)
                reflectionPerm3 = reflectionPerm1.Union(reflectionPerm2)

                If reflectionPerm3 Is Nothing Then
                    Console.WriteLine(("The union of " & reflection1.ToString() & " and " _
                    & reflection2.ToString() & " is null."))
                Else
                    Console.WriteLine(("The union of " & reflectionPerm1.Flags.ToString() & " and " _
                    & reflectionPerm2.Flags.ToString() & " = " _
                    & CType(reflectionPerm3, ReflectionPermission).Flags.ToString()))
                End If
ContinueWhile2:
            End While
ContinueWhile1:
        End While


        Return returnValue
    End Function 'UnionDemo

    ' Intersect creates and returns a new permission that is the intersection of the current 
    ' permission and the permission specified.
    Private Function IntersectDemo() As Boolean
        Dim returnValue As Boolean = True
        Dim reflection1, reflection2 As ReflectionPermissionFlag
        Dim reflectionPerm1, reflectionPerm2, reflectionPerm3 As ReflectionPermission
        Dim reflectionGen1 As New ReflectionGenerator()
        Dim reflectionGen2 As New ReflectionGenerator()
        reflectionGen1.ResetIndex()
        While reflectionGen1.CreateReflection(reflectionPerm1, reflection1)
            If reflectionPerm1 Is Nothing Then
                GoTo ContinueWhile1
            End If
            Console.WriteLine("**********************************************************" & ControlChars.Lf)
            reflectionGen2.ResetIndex()

            While reflectionGen2.CreateReflection(reflectionPerm2, reflection2)
                If reflectionPerm2 Is Nothing Then
                    GoTo ContinueWhile2
                End If
                reflectionPerm3 = CType(reflectionPerm1.Intersect(reflectionPerm2), ReflectionPermission)
                If Not (reflectionPerm3 Is Nothing) Then
                    Console.WriteLine(("The intersection of " & reflection1.ToString() & " and " _
                    & reflection2.ToString() & " = " _
                    & CType(reflectionPerm3, ReflectionPermission).Flags.ToString()))
                Else
                    Console.WriteLine(("The intersection of " & reflection1.ToString() & " and " _
                    & reflection2.ToString() & " is null."))
                End If
ContinueWhile2:
            End While
ContinueWhile1:
        End While

        Return returnValue
    End Function 'IntersectDemo

    'Copy creates and returns an identical copy of the current permission.
    Private Function CopyDemo() As Boolean

        Dim returnValue As Boolean = True

        Dim reflection1 As ReflectionPermissionFlag
        Dim reflectionPerm1, reflectionPerm2 As ReflectionPermission

        Dim reflectionGen1 As New ReflectionGenerator()
        Dim reflectionGen2 As New ReflectionGenerator()

        reflectionGen1.ResetIndex()
        While reflectionGen1.CreateReflection(reflectionPerm1, reflection1)
            If reflectionPerm1 Is Nothing Then
                GoTo ContinueWhile1
            End If
            reflectionGen2.ResetIndex()
            Console.WriteLine("********************************************************" & ControlChars.Lf)
            Try
                reflectionPerm2 = CType(reflectionPerm1.Copy(), ReflectionPermission)
                Console.WriteLine(("Result of copy = " & reflectionPerm2.ToString()))

            Catch e As Exception
                Console.WriteLine(("Copy failed :" & reflectionPerm1.ToString() & e.ToString()))
                GoTo ContinueWhile1
            End Try
ContinueWhile1:
        End While
        Return returnValue
    End Function 'CopyDemo

    ' ToXml creates an XML encoding of the permission and its current state; 
    ' FromXml reconstructs a permission with the specified state from the XML encoding. 
    Private Function ToFromXmlDemo() As Boolean

        Dim returnValue As Boolean = True

        Dim reflection1 As ReflectionPermissionFlag
        Dim reflectionPerm1, reflectionPerm2 As ReflectionPermission
        Dim reflectionGen1 As New ReflectionGenerator()
        Dim reflectionGen2 As New ReflectionGenerator()
        reflectionGen1.ResetIndex()
        While reflectionGen1.CreateReflection(reflectionPerm1, reflection1)
            If reflectionPerm1 Is Nothing Then
                GoTo ContinueWhile1
            End If
            Console.WriteLine("********************************************************" & ControlChars.Lf)
            reflectionGen2.ResetIndex()
            Try
                reflectionPerm2 = New ReflectionPermission(PermissionState.None)
                reflectionPerm2.FromXml(reflectionPerm1.ToXml())
                Console.WriteLine(("Result of ToFromXml = " & reflectionPerm2.ToString()))

            Catch e As Exception
                Console.WriteLine(("ToFromXml failed :" & reflectionPerm1.ToString() & e.ToString()))
                GoTo ContinueWhile1
            End Try
ContinueWhile1:
        End While

        Return returnValue
    End Function 'ToFromXmlDemo

    ' Invoke all demos.
    Public Function runDemo() As Boolean
        Dim returnCode As Boolean = True
        Dim tempReturnCode As Boolean

        ' Call the IsSubsetOf demo.
        tempReturnCode = IsSubsetOfDemo()
        If tempReturnCode Then
            Console.Out.WriteLine("IsSubsetOf demo completed successfully.")
        Else
            Console.Out.WriteLine("IsSubsetOf demo failed.")
        End If
        returnCode = tempReturnCode AndAlso returnCode

        ' Call the Union demo.
        tempReturnCode = UnionDemo()
        If tempReturnCode Then
            Console.Out.WriteLine("Union demo completed successfully.")
        Else
            Console.Out.WriteLine("Union demo failed.")
        End If
        returnCode = tempReturnCode AndAlso returnCode

        ' Call the Intersect demo.    
        tempReturnCode = IntersectDemo()
        If tempReturnCode Then
            Console.Out.WriteLine("Intersect demo completed successfully.")
        Else
            Console.Out.WriteLine("Intersect demo failed.")
        End If
        returnCode = tempReturnCode AndAlso returnCode


        ' Call the Copy demo.    
        tempReturnCode = CopyDemo()
        If tempReturnCode Then
            Console.Out.WriteLine("Copy demo completed successfully.")
        Else
            Console.Out.WriteLine("Copy demo failed.")
        End If
        returnCode = tempReturnCode AndAlso returnCode

        ' Call the ToFromXml demo.    
        tempReturnCode = ToFromXmlDemo()
        If tempReturnCode Then
            Console.Out.WriteLine("ToFromXml demo completed successfully.")
        Else
            Console.Out.WriteLine("ToFromXml demo failed.")
        End If
        returnCode = tempReturnCode AndAlso returnCode

        Return returnCode
    End Function 'runDemo

    ' Test harness.
    Public Overloads Shared Sub Main(ByVal args() As [String])
        Try
            Dim democase As New ReflectionPermissionDemo()
            Dim returnCode As Boolean = democase.runDemo()
            If returnCode Then
                Console.Out.WriteLine("ReflectionPermission demo completed successfully.")
                Console.Out.WriteLine("Press the Enter key to exit.")
                Dim consoleInput As String = Console.ReadLine()
                System.Environment.ExitCode = 100
            Else
                Console.Out.WriteLine("ReflectionPermission demo failed.")
                Console.Out.WriteLine("Press the Enter key to exit.")
                Dim consoleInput As String = Console.ReadLine()
                System.Environment.ExitCode = 101
            End If
        Catch e As Exception
            Console.Out.WriteLine("ReflectionPermission demo failed.")
            Console.WriteLine(e.ToString())
            Console.Out.WriteLine("Press the Enter key to exit.")
            Dim consoleInput As String = Console.ReadLine()
            System.Environment.ExitCode = 101
        End Try
    End Sub 'Main
End Class 'ReflectionPermissionDemo


' This class generates ReflectionPermission objects.

Friend Class ReflectionGenerator


    Private myReflection As ReflectionPermissionFlag() = {ReflectionPermissionFlag.AllFlags, ReflectionPermissionFlag.MemberAccess, ReflectionPermissionFlag.NoFlags, ReflectionPermissionFlag.ReflectionEmit, ReflectionPermissionFlag.TypeInformation}

    Private reflectionIndex As Integer = 0


    Public Sub New()
        ResetIndex()
    End Sub 'New


    Public Sub ResetIndex()
        reflectionIndex = 0
    End Sub 'ResetIndex

    ' CreateReflection creates a ReflectionPermission object.
    Public Function CreateReflection(ByRef reflectionPerm As ReflectionPermission, ByRef reflection As ReflectionPermissionFlag) As Boolean

        If reflectionIndex >= myReflection.Length Then
            reflectionPerm = New ReflectionPermission(PermissionState.None)
            reflection = ReflectionPermissionFlag.NoFlags
            reflectionIndex &= 1
            Return False
        End If
        reflection = myReflection(reflectionIndex)
        reflectionIndex = reflectionIndex + 1
        Try
            reflectionPerm = New ReflectionPermission(reflection)
            Return True
        Catch e As Exception
            Console.WriteLine(("Cannot create ReflectionPermission: " & reflection & " " & e.ToString()))
            reflectionPerm = New ReflectionPermission(PermissionState.None)
            reflection = ReflectionPermissionFlag.NoFlags
            Return True
        End Try
    End Function 'CreateReflection
' End of ReflectionGenerator.

[C#] 
// This sample demonstrates the IsSubsetOf, Union, Intersect, Copy, ToXml and FromXml methods 
// of the ReflectionPermission class.

using System;
using System.Security; 
using System.Security.Permissions; 

[assembly:CLSCompliant(true)]

public class ReflectionPermissionDemo
{
    // IsSubsetOf determines whether the current permission is a subset of the specified permission.
    private bool IsSubsetOfDemo()
    {
        bool returnValue = true;
        ReflectionPermissionFlag reflection1,reflection2;
        ReflectionPermission reflectionPerm1,reflectionPerm2;
        ReflectionGenerator reflectionGen1 = new ReflectionGenerator();
        ReflectionGenerator reflectionGen2 = new ReflectionGenerator();
        reflectionGen1.ResetIndex();
        while(reflectionGen1.CreateReflection(out reflectionPerm1, out reflection1)) 
        {
            if(reflectionPerm1 == null) continue;
            reflectionGen2.ResetIndex();
            Console.WriteLine("********************************************************\n");

            while(reflectionGen2.CreateReflection(out reflectionPerm2, out reflection2)) 
            {
                if(reflectionPerm2 == null) continue;
                try
                {            
                    if (reflectionPerm1.IsSubsetOf(reflectionPerm2))
                    {
                        Console.WriteLine(reflectionPerm1.Flags + " is a subset of " + 
                            reflectionPerm2.Flags);
                    }
                    else
                    {
                        Console.WriteLine(reflectionPerm1.Flags + " is not a subset of " + 
                            reflectionPerm2.Flags);
                    }
                }
                catch(Exception e) 
                {
                    Console.WriteLine("An exception was thrown for subset :" + reflectionPerm1 + "\n" + 
                        reflectionPerm2 +"\n" + e);
                    returnValue=false;
                }
            }
        }
        return returnValue;
    }
    // Union creates a new permission that is the union of the current permission and the specified permission.
    private bool UnionDemo()
    {
        bool returnValue = true;
        ReflectionPermissionFlag reflection1,reflection2;
        ReflectionPermission reflectionPerm1,reflectionPerm2;
        IPermission reflectionPerm3;
        ReflectionGenerator reflectionGen1 = new ReflectionGenerator();
        ReflectionGenerator reflectionGen2 = new ReflectionGenerator();
        reflectionGen1.ResetIndex();
        while(reflectionGen1.CreateReflection(out reflectionPerm1, out reflection1)) 
        {
            if(reflectionPerm1 == null) continue;
            Console.WriteLine("**********************************************************\n");
            reflectionGen2.ResetIndex();

            while(reflectionGen2.CreateReflection(out reflectionPerm2, out reflection2)) 
            {
                if(reflectionPerm2 == null) continue;
                reflectionPerm3 = (ReflectionPermission)reflectionPerm1.Union(reflectionPerm2);
                reflectionPerm3 = reflectionPerm1.Union(reflectionPerm2);

                if(reflectionPerm3 == null)  
                {
                    Console.WriteLine("The union of " +  reflection1 + " and " + reflection2 + " is null." );
                }
                else
                {
                    Console.WriteLine("The union of " + reflectionPerm1.Flags + " and " + 
                        reflectionPerm2.Flags + " = " + 
                        ((ReflectionPermission)reflectionPerm3).Flags.ToString());
                }

            }
        }

        return returnValue;

    }
    // Intersect creates and returns a new permission that is the intersection of the current 
    // permission and the permission specified.
    private bool IntersectDemo()
    {
        bool returnValue = true;
        ReflectionPermissionFlag reflection1,reflection2;
        ReflectionPermission reflectionPerm1,reflectionPerm2,reflectionPerm3;
        ReflectionGenerator reflectionGen1 = new ReflectionGenerator();
        ReflectionGenerator reflectionGen2 = new ReflectionGenerator();
        reflectionGen1.ResetIndex();
        while(reflectionGen1.CreateReflection(out reflectionPerm1, out reflection1)) 
        {
            if(reflectionPerm1 == null) continue;
            Console.WriteLine("**********************************************************\n");
            reflectionGen2.ResetIndex();

            while(reflectionGen2.CreateReflection(out reflectionPerm2, out reflection2)) 
            {
                if(reflectionPerm2 == null) continue;
    
                reflectionPerm3 = (ReflectionPermission)reflectionPerm1.Intersect(reflectionPerm2);
                if (reflectionPerm3 != null)
                {
                    Console.WriteLine("The intersection of " + reflection1 + " and " + reflection2 + " = " + 
                        ((ReflectionPermission)reflectionPerm3).Flags.ToString());
                }
                else
                {
                    Console.WriteLine("The intersection of " + reflection1 + " and " + reflection2 + " is null." );
                }
            }
        }

        return returnValue;
    }
    //Copy creates and returns an identical copy of the current permission.
    private bool CopyDemo()
    {

        bool returnValue = true;

        ReflectionPermissionFlag reflection1;
        ReflectionPermission reflectionPerm1,reflectionPerm2;

        ReflectionGenerator reflectionGen1 = new ReflectionGenerator();
        ReflectionGenerator reflectionGen2 = new ReflectionGenerator();

        reflectionGen1.ResetIndex();
        while(reflectionGen1.CreateReflection(out reflectionPerm1, out reflection1)) 
        {
            if(reflectionPerm1 == null) continue;
            reflectionGen2.ResetIndex();
            Console.WriteLine("********************************************************\n");
            try
            {            
                reflectionPerm2 = (ReflectionPermission)reflectionPerm1.Copy();
                Console.WriteLine("Result of copy = " + reflectionPerm2.ToString());

            }
            catch(Exception e) 
            {
                Console.WriteLine("Copy failed :" + reflectionPerm1.ToString() + e);
                continue;
            }
        }
        return returnValue;
    }
    // ToXml creates an XML encoding of the permission and its current state; 
    // FromXml reconstructs a permission with the specified state from the XML encoding. 
    private bool ToFromXmlDemo()
    {

        bool returnValue = true;

        ReflectionPermissionFlag reflection1;
        ReflectionPermission reflectionPerm1,reflectionPerm2;
        ReflectionGenerator reflectionGen1 = new ReflectionGenerator();
        ReflectionGenerator reflectionGen2 = new ReflectionGenerator();
        reflectionGen1.ResetIndex();
        while(reflectionGen1.CreateReflection(out reflectionPerm1, out reflection1)) 
        {
            if(reflectionPerm1 == null) continue;
            Console.WriteLine("********************************************************\n");
            reflectionGen2.ResetIndex();
            try
            {            
                reflectionPerm2= new ReflectionPermission(PermissionState.None);
                reflectionPerm2.FromXml(reflectionPerm1.ToXml());
                Console.WriteLine("Result of ToFromXml = " +
                    reflectionPerm2.ToString());
    
            }
            catch(Exception e) 
            {
                Console.WriteLine("ToFromXml failed :" + reflectionPerm1.ToString() + e);
                continue;
            }
        }

        return returnValue;

    }
    // Invoke all demos.
    public bool runDemo()
    {
        bool returnCode = true;
        bool tempReturnCode;

        // Call the IsSubsetOf demo.
        if(tempReturnCode= IsSubsetOfDemo())Console.Out.WriteLine("IsSubsetOf demo completed successfully.");
        else Console.Out.WriteLine("IsSubsetOf demo failed.");
        returnCode=tempReturnCode && returnCode;

        // Call the Union demo.
        if(tempReturnCode= UnionDemo())Console.Out.WriteLine("Union demo completed successfully.");
        else Console.Out.WriteLine("Union demo failed.");
        returnCode=tempReturnCode && returnCode;

        // Call the Intersect demo.    
        if(tempReturnCode= IntersectDemo())Console.Out.WriteLine("Intersect demo completed successfully.");
        else Console.Out.WriteLine("Intersect demo failed.");
        returnCode=tempReturnCode && returnCode;


        // Call the Copy demo.    
        if(tempReturnCode= CopyDemo())Console.Out.WriteLine("Copy demo completed successfully.");
        else Console.Out.WriteLine("Copy demo failed.");
        returnCode=tempReturnCode && returnCode;

        // Call the ToFromXml demo.    
        if(tempReturnCode= ToFromXmlDemo())Console.Out.WriteLine("ToFromXml demo completed successfully.");
        else Console.Out.WriteLine("ToFromXml demo failed.");
        returnCode=tempReturnCode && returnCode;

        return (  returnCode );    
    }
    // Test harness.
    public static void Main(String[] args) 
    {
        try
        {
            ReflectionPermissionDemo democase = new ReflectionPermissionDemo();
            bool returnCode = democase.runDemo();
            if (returnCode)
            {
                Console.Out.WriteLine("ReflectionPermission demo completed successfully.");
                Console.Out.WriteLine("Press the Enter key to exit.");
                string consoleInput = Console.ReadLine();
                System.Environment.ExitCode = 100;
            }
            else
            {
                Console.Out.WriteLine("ReflectionPermission demo failed.");
                Console.Out.WriteLine("Press the Enter key to exit.");
                string consoleInput = Console.ReadLine();
                System.Environment.ExitCode = 101;
            }
        }
        catch(Exception e)
        {
            Console.Out.WriteLine("ReflectionPermission demo failed.");
            Console.WriteLine(e.ToString());
            Console.Out.WriteLine("Press the Enter key to exit.");
            string consoleInput = Console.ReadLine();
            System.Environment.ExitCode = 101;
        }
    }
}


// This class generates ReflectionPermission objects.

internal  class ReflectionGenerator
{


    private ReflectionPermissionFlag[] myReflection = 
        {ReflectionPermissionFlag.AllFlags,
         ReflectionPermissionFlag.MemberAccess,
         ReflectionPermissionFlag.NoFlags,
         ReflectionPermissionFlag.ReflectionEmit,
         ReflectionPermissionFlag.TypeInformation};

    private int reflectionIndex = 0;

    public ReflectionGenerator()
    {
        ResetIndex();
    }

    public void ResetIndex()
    {
        reflectionIndex = 0;
    }
    // CreateReflection creates a ReflectionPermission object.
    public bool CreateReflection(out ReflectionPermission reflectionPerm, 
        out ReflectionPermissionFlag reflection)
    {

        if(reflectionIndex >= myReflection.Length) 
        {
            reflectionPerm = new ReflectionPermission(PermissionState.None);
            reflection=ReflectionPermissionFlag.NoFlags;
            reflectionIndex++;
            return false;
        }
        reflection = myReflection[reflectionIndex++];
        try
        {
            reflectionPerm = new ReflectionPermission(reflection);
            return true;
        } 
        catch(Exception e)
        {
            Console.WriteLine("Cannot create ReflectionPermission: " + reflection +" "+e);
            reflectionPerm = new ReflectionPermission(PermissionState.None);
            reflection=ReflectionPermissionFlag.NoFlags;
            return true;
        }
    }
} // End of ReflectionGenerator.

[C++] 
// This sample demonstrates the IsSubsetOf, Union, Intersect, Copy, ToXml and FromXml methods
// of the ReflectionPermission class.

#using <mscorlib.dll>

using namespace System;
using namespace System::Security;
using namespace System::Security::Permissions;
using namespace System::Runtime::InteropServices;

[assembly:CLSCompliant(true)];

// This class generates ReflectionPermission objects.

private __gc class ReflectionGenerator {

private:
   ReflectionPermissionFlag myReflection[];
   int  reflectionIndex;

public:
   ReflectionGenerator() {

      ReflectionPermissionFlag temp0 [] = {
         ReflectionPermissionFlag::AllFlags,
            ReflectionPermissionFlag::MemberAccess,
            ReflectionPermissionFlag::NoFlags,
            ReflectionPermissionFlag::ReflectionEmit,
            ReflectionPermissionFlag::TypeInformation};

         myReflection = temp0;

         ResetIndex();
   }

public:
   void ResetIndex() {
      reflectionIndex = 0;
   }
   // CreateReflection creates a ReflectionPermission object.
public:
   bool CreateReflection([Out]ReflectionPermission** reflectionPerm,
      [Out] ReflectionPermissionFlag* reflection) {

         if (reflectionIndex >= myReflection->Length) {
            *reflectionPerm = new ReflectionPermission(PermissionState::None);
            *reflection=ReflectionPermissionFlag::NoFlags;
            reflectionIndex++;
            return false;
         }
         *reflection = myReflection[reflectionIndex++];
         try {
            *reflectionPerm = new ReflectionPermission(*reflection);
            return true;
         } catch (Exception* e) {
            Console::WriteLine(S"Cannot create ReflectionPermission: {0} {1}", __box(*reflection), e);
            *reflectionPerm = new ReflectionPermission(PermissionState::None);
            *reflection=ReflectionPermissionFlag::NoFlags;
            return true;
         }
      }
}; // End of ReflectionGenerator.

public __gc class ReflectionPermissionDemo {
   // IsSubsetOf determines whether the current permission is a subset of the specified permission.
private:
   bool IsSubsetOfDemo() {
      bool returnValue = true;
      ReflectionPermissionFlag reflection1, reflection2;
      ReflectionPermission* reflectionPerm1, *reflectionPerm2;
      ReflectionGenerator* reflectionGen1 = new ReflectionGenerator();
      ReflectionGenerator* reflectionGen2 = new ReflectionGenerator();
      reflectionGen1->ResetIndex();
      while(reflectionGen1->CreateReflection(&reflectionPerm1, &reflection1)) {
         if (reflectionPerm1 == 0) continue;
         reflectionGen2->ResetIndex();
         Console::WriteLine(S"********************************************************\n");

         while(reflectionGen2->CreateReflection(&reflectionPerm2, &reflection2)) {
            if (reflectionPerm2 == 0) continue;
            try {
               if (reflectionPerm1->IsSubsetOf(reflectionPerm2)) {
                  Console::WriteLine(S"{0} is a subset of {1}",
                     __box(reflectionPerm1->Flags), __box(reflectionPerm2->Flags));
               } else {
                  Console::WriteLine(S"{0} is not a subset of {1}",
                     __box(reflectionPerm1->Flags), __box(reflectionPerm2->Flags));
               }
            } catch (Exception* e) {
               Console::WriteLine(S"An exception was thrown for subset : {0}\n{1}\n{2}",
                  reflectionPerm1, reflectionPerm2, e);
               returnValue=false;
            }
         }
      }
      return returnValue;
   }
   // Union creates a new permission that is the union of the current permission and the specified permission.
private:
   bool UnionDemo() {
      bool returnValue = true;
      ReflectionPermissionFlag reflection1, reflection2;
      ReflectionPermission* reflectionPerm1, *reflectionPerm2;
      IPermission* reflectionPerm3;
      ReflectionGenerator* reflectionGen1 = new ReflectionGenerator();
      ReflectionGenerator* reflectionGen2 = new ReflectionGenerator();
      reflectionGen1->ResetIndex();
      while(reflectionGen1->CreateReflection(&reflectionPerm1, &reflection1)) {
         if (reflectionPerm1 == 0) continue;
         Console::WriteLine(S"**********************************************************\n");
         reflectionGen2->ResetIndex();

         while(reflectionGen2->CreateReflection(&reflectionPerm2, &reflection2)) {
            if (reflectionPerm2 == 0) continue;
            reflectionPerm3 = dynamic_cast<ReflectionPermission*>(reflectionPerm1->Union(reflectionPerm2));
            reflectionPerm3 = reflectionPerm1->Union(reflectionPerm2);

            if (reflectionPerm3 == 0) {
               Console::WriteLine(S"The union of {0} and {1} is null.", __box(reflection1), __box(reflection2));
            } else {
               Console::WriteLine(S"The union of {0} and {1} = {2}",
                  __box(reflectionPerm1->Flags),
                  __box(reflectionPerm2->Flags),
                  __box((dynamic_cast<ReflectionPermission*>(reflectionPerm3))->Flags));
            }

         }
      }
      return returnValue;
   }
   // Intersect creates and returns a new permission that is the intersection of the current
   // permission and the permission specified.
private:
   bool IntersectDemo() {
      bool returnValue = true;
      ReflectionPermissionFlag reflection1, reflection2;
      ReflectionPermission* reflectionPerm1, *reflectionPerm2, *reflectionPerm3;
      ReflectionGenerator* reflectionGen1 = new ReflectionGenerator();
      ReflectionGenerator* reflectionGen2 = new ReflectionGenerator();
      reflectionGen1->ResetIndex();
      while(reflectionGen1->CreateReflection(&reflectionPerm1, &reflection1)) {
         if (reflectionPerm1 == 0) continue;
         Console::WriteLine(S"**********************************************************\n");
         reflectionGen2->ResetIndex();

         while(reflectionGen2->CreateReflection(&reflectionPerm2, &reflection2)) {
            if (reflectionPerm2 == 0) continue;

            reflectionPerm3 = dynamic_cast<ReflectionPermission*>(reflectionPerm1->Intersect(reflectionPerm2));
            if (reflectionPerm3 != 0) {
               Console::WriteLine(S"The intersection of {0} and {1} = {2}", __box(reflection1), __box(reflection2),
                  __box((dynamic_cast<ReflectionPermission*>(reflectionPerm3))->Flags));
            } else {
               Console::WriteLine(S"The intersection of {0} and {1} is null", __box(reflection1), __box(reflection2));
            }
         }
      }

      return returnValue;
   }
   //Copy creates and returns an identical copy of the current permission.
private:
   bool CopyDemo() {

      bool returnValue = true;

      ReflectionPermissionFlag reflection1;
      ReflectionPermission* reflectionPerm1, *reflectionPerm2;

      ReflectionGenerator* reflectionGen1 = new ReflectionGenerator();
      ReflectionGenerator* reflectionGen2 = new ReflectionGenerator();

      reflectionGen1->ResetIndex();
      while(reflectionGen1->CreateReflection(&reflectionPerm1, &reflection1)) {
         if (reflectionPerm1 == 0) continue;
         reflectionGen2->ResetIndex();
         Console::WriteLine(S"********************************************************\n");
         try {
            reflectionPerm2 = dynamic_cast<ReflectionPermission*>(reflectionPerm1->Copy());
            Console::WriteLine(S"Result of copy = {0}", reflectionPerm2);

         } catch (Exception* e) {
            Console::WriteLine(S"Copy failed : {0}{1}", reflectionPerm1, e);
            continue;
         }
      }
      return returnValue;
   }
   // ToXml creates an XML encoding of the permission and its current state;
   // FromXml reconstructs a permission with the specified state from the XML encoding.
private:
   bool ToFromXmlDemo() {

      bool returnValue = true;

      ReflectionPermissionFlag reflection1;
      ReflectionPermission* reflectionPerm1, *reflectionPerm2;
      ReflectionGenerator* reflectionGen1 = new ReflectionGenerator();
      ReflectionGenerator* reflectionGen2 = new ReflectionGenerator();
      reflectionGen1->ResetIndex();
      while(reflectionGen1->CreateReflection(&reflectionPerm1, &reflection1)) {
         if (reflectionPerm1 == 0) continue;
         Console::WriteLine(S"********************************************************\n");
         reflectionGen2->ResetIndex();
         try {
            reflectionPerm2 = new ReflectionPermission(PermissionState::None);
            reflectionPerm2->FromXml(reflectionPerm1->ToXml());
            Console::WriteLine(S"Result of ToFromXml = {0}", reflectionPerm2);

         } catch (Exception* e) {
            Console::WriteLine(S"ToFromXml failed : {0}{1}", reflectionPerm1, e);
            continue;
         }
      }

      return returnValue;

   }
   // Invoke all demos.
public:
   bool runDemo() {
      bool returnCode = true;
      bool tempReturnCode;

      // Call the IsSubsetOf demo.
      if (tempReturnCode= IsSubsetOfDemo())Console::WriteLine(S"IsSubsetOf demo completed successfully.");
      else Console::WriteLine(S"IsSubsetOf demo failed.");
      returnCode=tempReturnCode && returnCode;

      // Call the Union demo.
      if (tempReturnCode= UnionDemo())Console::WriteLine(S"Union demo completed successfully.");
      else Console::WriteLine(S"Union demo failed.");
      returnCode=tempReturnCode && returnCode;

      // Call the Intersect demo.
      if (tempReturnCode= IntersectDemo())Console::WriteLine(S"Intersect demo completed successfully.");
      else Console::WriteLine(S"Intersect demo failed.");
      returnCode=tempReturnCode && returnCode;

      // Call the Copy demo.
      if (tempReturnCode= CopyDemo())Console::WriteLine(S"Copy demo completed successfully.");
      else Console::WriteLine(S"Copy demo failed.");
      returnCode=tempReturnCode && returnCode;

      // Call the ToFromXml demo.
      if (tempReturnCode= ToFromXmlDemo())Console::WriteLine(S"ToFromXml demo completed successfully.");
      else Console::WriteLine(S"ToFromXml demo failed.");
      returnCode=tempReturnCode && returnCode;

      return (returnCode);
   }
};


// Test harness.
int main() {
   try {
      ReflectionPermissionDemo* democase = new ReflectionPermissionDemo();
      bool returnCode = democase->runDemo();
      if (returnCode) {
         Console::WriteLine(S"ReflectionPermission demo completed successfully.");
         Console::WriteLine(S"Press the Enter key to exit.");
         Console::ReadLine();
         System::Environment::ExitCode = 100;
      } else {
         Console::WriteLine(S"ReflectionPermission demo failed.");
         Console::WriteLine(S"Press the Enter key to exit.");
         Console::ReadLine();
         System::Environment::ExitCode = 101;
      }
   } catch (Exception* e) {
      Console::WriteLine(S"ReflectionPermission demo failed.");
      Console::WriteLine(e);
      Console::WriteLine(S"Press the Enter key to exit.");
      Console::ReadLine();
      System::Environment::ExitCode = 101;
   }
}

[JScript] JScript のサンプルはありません。Visual Basic、C#、および C++ のサンプルを表示するには、このページの左上隅にある言語のフィルタ ボタン 言語のフィルタ をクリックします。

必要条件

名前空間: System.Security.Permissions

プラットフォーム: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 ファミリ

アセンブリ: Mscorlib (Mscorlib.dll 内)

参照

ReflectionPermission メンバ | System.Security.Permissions 名前空間 | アクセス許可 | アクセス許可の要求 | ReflectionPermissionAttribute | ReflectionPermissionFlag