code_junkie

How can you require a constructor with no parameters for types implementing an interface?

Nov 10th, 2011
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. public class Something : ITest<String>
  2. {
  3. private Something() { }
  4. }
  5.  
  6. public interface ITest<T>
  7. where T : ITest<T>, new()
  8. {
  9. }
  10.  
  11. public class A : ITest<A>
  12. {
  13. }
  14.  
  15. public class B : ITest<A>
  16. {
  17. private B() { }
  18. }
  19.  
  20. interface ITest<T> where T: new()
  21. {
  22. //...
  23. }
  24.  
  25. class Test: ITest<Test>
  26. {
  27. //...
  28. }
  29.  
  30. public interface IInterface
  31. {
  32. void DoSomething();
  33. }
  34.  
  35. public class Foo : IInterface
  36. {
  37. public void DoSomething() { /* whatever */ }
  38. }
  39.  
  40. public IInterface CreateUsingType(Type thingThatCreates)
  41. {
  42. ConstructorInfo constructor = thingThatCreates.GetConstructor(Type.EmptyTypes);
  43. return (IInterface)constructor.Invoke(new object[0]);
  44. }
  45.  
  46. public void Test()
  47. {
  48. IInterface thing = CreateUsingType(typeof(Foo));
  49. }
  50.  
  51. public interface IFactory
  52. {
  53. IInterface Create();
  54. }
  55.  
  56. public class Factory<T> where T : IInterface, new()
  57. {
  58. public IInterface Create() { return new T(); }
  59. }
  60.  
  61. public IInterface CreateUsingFactory(IFactory factory)
  62. {
  63. return factory.Create();
  64. }
  65.  
  66. public void Test()
  67. {
  68. IInterface thing = CreateUsingFactory(new Factory<Foo>());
  69. }
  70.  
  71. public IInterface CreateUsingDelegate(Func<IInterface> createCallback)
  72. {
  73. return createCallback();
  74. }
  75.  
  76. public void Test()
  77. {
  78. IInterface thing = CreateUsingDelegate(() => new Foo());
  79. }
  80.  
  81. void RegisterType<T>() where T:ITest, new() {
  82. }
  83.  
  84. interface FooFactory {
  85. Foo createInstance();
  86. }
Add Comment
Please, Sign In to add comment