日期:2013-01-15  浏览次数:20453 次

// Snippet shows how interfaces and coclasses can adorn the Guid attribute.
// Running the regasm will generate .reg and .tlb files. Reg file can be
// used to register the interface and coclass with the registry. Tlb file
// are used to do interop. Also illustrates how System.Guid can be constructed
// and how guid objects can be compared.

namespace GuidSnippet
{
    //<Snippet1>
    using System;
    using System.Runtime.InteropServices;

    // Guid for the interface IFoo.
    [Guid("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4")]
    interface IFoo
    {
        void Foo();
    }

    // Guid for the coclass CFoo.
    [Guid("936DA01F-9ABD-4d9d-80C7-02AF85C822A8")]
    public class CFoo : IFoo
    {
        // Run regasm on this assembly to create .reg and .tlb files.
        // Reg file can be used to register this coclass in the registry.
        // Tlb file will be used to do interop.

        public void Foo() {}

        public static void Main( string []args )
        {
            // Snippet addresses the following in System.Runtime.InterOpServices.GuidAttribute.
            // How to specify the attribute on interface/coclass.
            // Retrieve the GuidAttribute from an interface/coclass.
            // Value property on GuidAttribute class.

            // Snippet addresses the following in System.Guid.
            // Constructor Guid(string).
            // Constructor Guid(ByteArray).
            // Equals.
            // Operator ==.
            // CompareTo.

            Attribute IFooAttribute = Attribute.GetCustomAttribute( typeof( IFoo ), typeof( GuidAttribute ) );
            
            // The Value property of GuidAttribute returns a string.
            System.Console.WriteLine( "IFoo Attribute: " + ((GuidAttribute)IFooAttribute).Value );    

            // Using the string to create a guid.
            Guid guidFoo1 = new Guid( ((GuidAttribute)IFooAttribute).Value );
            // Using a byte array to create a guid.
            Guid guidFoo2 = new Guid ( guidFoo1.ToByteArray() );

           &nb