using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DynamicCheckForFactory
{
interface ISomething
{
}
static class SomethingChecker
{
public static Func<T> CheckAndGetBuider<T>() where T : ISomething
{
var type = typeof(T);
var builder = type.GetMethod("GetInstance",
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
if (builder == null)
throw new Exception();
return () => (T)builder.Invoke(null, null);
}
}
class GoodSomething : ISomething
{
static public GoodSomething GetInstance()
{
return new GoodSomething();
}
}
class BadSomething : ISomething
{
}
class Program
{
static void Main(string[] args)
{
try
{
var goodBuilder = SomethingChecker.CheckAndGetBuider<GoodSomething>();
var goodInstance = goodBuilder();
Console.WriteLine("good instance obtained");
}
catch
{
Console.WriteLine("cannot obtain good instance");
}
try
{
var badBuilder = SomethingChecker.CheckAndGetBuider<BadSomething>();
var badInstance = badBuilder();
Console.WriteLine("bad instance obtained");
}
catch
{
Console.WriteLine("cannot obtain bad instance");
}
}
}
}