0

interfaceと呼ばれるものがあるとしますIVerifier

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

リフレクションによってアセンブリをロードする必要があり、そのアセンブリは同じ署名を保持しています。これを行う方法は次のとおりです。

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

そして中GetValidations()にはリフレクションが常駐!

私はこれについて多くのことを考えてきましたが、リフレクトされたメソッドの呼び出しは 内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 に答える