首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >反射问题

反射问题
EN

Stack Overflow用户
提问于 2013-01-31 23:08:15
回答 1查看 85关注 0票数 0

假设我有一个名为IVerifierinterface

代码语言:javascript
复制
public interface IVerifier
{
  bool Validate(byte[]x, byte[]y);
}

我必须通过反射加载一个程序集,该程序集具有相同的签名,这是如何可能的:

代码语言:javascript
复制
IVerifier c = GetValidations();
c.Validate(x,y);

而在GetValidations()内部是驻留的反射!

我一直在思考这个问题,我得到的结论是,调用反射方法将在GetValidations()内部进行,但它必须像上面这样做。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-01 00:20:15

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

代码语言:javascript
复制
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.");       
}

示例用法:

代码语言:javascript
复制
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!");
        }
    }

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14628894

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档