假设我有interface
名为IVerifier
public interface IVerifier
{
bool Validate(byte[]x, byte[]y);
}
我必须通过反射加载一个程序集,并且该程序集保持相同的签名,这样做的可能性如何:
IVerifier c = GetValidations();
c.Validate(x,y);
内部GetValidations()
是反射所在!
我一直在考虑这个问题,而且我得到的是调用反射方法将在GetValidations()
内部,但它必须像上面那样去做。
答案 0 :(得分: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!");
}
}
}