0

假设我有一个interface被叫IVerifier

public interface IVerifier
{
  bool Validate(byte[]x, byte[]y);
}

我不得不通过反射加载一个程序集,并且该程序集拥有相同的签名,这样做有多大可能:

IVerifier c = GetValidations();
c.Validate(x,y);

里面GetValidations()是反射所在!

我一直在考虑这个问题,我得到的只是调用反射方法将在 inside GetValidations(),但它必须像上面那样做。

4

1 回答 1

1

假设您不知道要在另一个程序集中实例化的类型,您只知道它实现IVerifier了您可以使用如下方法:

static TInterface GetImplementation<TInterface>( Assembly assembly)
{
    var types = assembly.GetTypes();
    Type implementationType = types.SingleOrDefault(t => typeof (TInterface).IsAssignableFrom(t) && t.IsClass);


    if (implementationType != null)
    {
        TInterface implementation = (TInterface)Activator.CreateInstance(implementationType);
        return implementation;
    }

    throw new Exception("No Type implements interface.");       
}

样品用途:

using System;
using System.Linq;
using System.Reflection;

namespace ConsoleApplication9
{
    class Program
    {
        static void Main(string[] args)
        {
            IHelloWorld x = GetImplementation<IHelloWorld>(Assembly.GetExecutingAssembly());

            x.SayHello();
            Console.ReadKey();

        }
        static TInterface GetImplementation<TInterface>( Assembly assembly)
        {
            var types = assembly.GetTypes();
            Type implementationType = types.SingleOrDefault(t => typeof (TInterface).IsAssignableFrom(t) && t.IsClass);


            if (implementationType != null)
            {
                TInterface implementation = (TInterface)Activator.CreateInstance(implementationType);
                return implementation;
            }

            throw new Exception("No Type implements interface.");

        }
    }
    interface IHelloWorld
    {
        void SayHello();
    }
    class MyImplementation : IHelloWorld
    {
        public void SayHello()
        {
            Console.WriteLine("Hello world from MyImplementation!");
        }
    }

}
于 2013-01-31T16:20:15.423 回答