using System;
using System.Collections;
using System.Runtime.Remoting;

namespace Utilities
{
    /// <summary>
    /// This class is used to obtain a Remoting object from a registered list of well known client
    /// types. Use this class instead of manually calling Activator.GetObject.
    /// </summary>
    /// <remarks>This class was taken from the book "Advanced .NET Remoting" by Ingo Rammer (pg. 185-186).</remarks>
    public class RemotingHelper
    {
        private static bool m_isInit;
        private static IDictionary m_wellKnownTypes;

        // Constructor made private to prevent unwanted instantiation
        private RemotingHelper() { }

        /// <summary>
        /// Used to get the Remoting object.
        /// </summary>
        /// <param name="type">The type of object to get.</param>
        /// <returns>An Object representing the well known type.</returns>
        /// <exception cref="System.Runtime.Remoting.RemotingException">Thrown when the type is not found.</exception>
        /// <example>
        /// <code>
        ///     ICustomType obj = (ICustomType)RemotingHelper.GetObject(typeof(ICustomType));
        /// </code>
        /// </example>
        public static Object GetObject(Type type)
        {
            if (!m_isInit)
            {
                InitTypeCache();
            }

            WellKnownClientTypeEntry entr = (WellKnownClientTypeEntry) m_wellKnownTypes[type];
            if (entr == null)
            {
                string asmName = type.Assembly.GetName().Name;
                string typeName = type.ToString();
                string msg = string.Format("Type '{0}' not found in assembly '{1}'", typeName, asmName);
                throw new RemotingException(msg);
            }

            return Activator.GetObject(entr.ObjectType, entr.ObjectUrl);
        }

        private static void InitTypeCache() 
        {
            m_isInit = true;

            m_wellKnownTypes= new Hashtable();
            foreach (WellKnownClientTypeEntry entr in RemotingConfiguration.GetRegisteredWellKnownClientTypes()) 
            {
                if (entr.ObjectType == null)
                {
                    string msg = string.Format("Configured well-known client entry '{0}' could not be found", entr.ToString());
                    throw new RemotingException(msg);
                }
                m_wellKnownTypes.Add(entr.ObjectType, entr);
            }
        }
    }
}

C#远程访问通用类