fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace DynamicCheckForFactory
  8. {
  9. interface ISomething
  10. {
  11. }
  12.  
  13. static class SomethingChecker
  14. {
  15. public static Func<T> CheckAndGetBuider<T>() where T : ISomething
  16. {
  17. var type = typeof(T);
  18. var builder = type.GetMethod("GetInstance",
  19. System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
  20. if (builder == null)
  21. throw new Exception();
  22. return () => (T)builder.Invoke(null, null);
  23. }
  24. }
  25.  
  26. class GoodSomething : ISomething
  27. {
  28. static public GoodSomething GetInstance()
  29. {
  30. return new GoodSomething();
  31. }
  32. }
  33.  
  34. class BadSomething : ISomething
  35. {
  36. }
  37.  
  38. class Program
  39. {
  40. static void Main(string[] args)
  41. {
  42. try
  43. {
  44. var goodBuilder = SomethingChecker.CheckAndGetBuider<GoodSomething>();
  45. var goodInstance = goodBuilder();
  46. Console.WriteLine("good instance obtained");
  47. }
  48. catch
  49. {
  50. Console.WriteLine("cannot obtain good instance");
  51. }
  52.  
  53. try
  54. {
  55. var badBuilder = SomethingChecker.CheckAndGetBuider<BadSomething>();
  56. var badInstance = badBuilder();
  57. Console.WriteLine("bad instance obtained");
  58. }
  59. catch
  60. {
  61. Console.WriteLine("cannot obtain bad instance");
  62. }
  63. }
  64. }
  65. }
  66.  
Success #stdin #stdout 0.03s 24208KB
stdin
Standard input is empty
stdout
good instance obtained
cannot obtain bad instance