假设我有一个名为IVerifier的interface
public interface IVerifier
{
bool Validate(byte[]x, byte[]y);
}我必须通过反射加载一个程序集,该程序集具有相同的签名,这是如何可能的:
IVerifier c = GetValidations();
c.Validate(x,y);而在GetValidations()内部是驻留的反射!
我一直在思考这个问题,我得到的结论是,调用反射方法将在GetValidations()内部进行,但它必须像上面这样做。
发布于 2013-02-01 00:20:15
假设你不知道你想在另一个程序集中实例化的类型,你只知道它实现了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!");
}
}
}https://stackoverflow.com/questions/14628894
复制相似问题