How in the Generic method of a class to call a method not belonging to an object without imposing a restriction on the type? The test for the existence of a method has already been done through reflection (i.e., this instance definitely has a method). Instance can not be given through as because it inherits only Object and does not implement any interface.

class SomeClass<T> { void Foo(T a) { a.SomeMethod(); } } 
  • You want something wrong. And if someone starts it not for your object? As an option - run the same reflection, since it checked availability. - Monk
  • @ YanGermanovich, yes, quite an option. You can answer your own question. - Surfin Bird
  • Anyway, thanks for the help) - Jan Germanovich
  • The meaning of using the generic method is not completely clear - Grundy

2 answers 2

Already found a solution through dynamic

 class SomeClass<T> { void Foo(T a) { dynamic r = a; r.SomeMethod(); } } 
  • 2
    Why so hard? Why not cast to the right type? - VladD 6:39

Generally speaking, it would be better to build a delegate for access in the same place where you check that the method exists. More precisely, the process of building such a delegate itself would be such a check:

 class SomeClass<T> { static readonly Action<T> SomeMethodInvoker; static SomeClass() { var p = Expression.Parameter(typeof(T)); // Π‘Ρ‚Ρ€ΠΎΠΊΠ° Π½ΠΈΠΆΠ΅ ΠΊΠΈΠ½Π΅Ρ‚ ΠΈΡΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΠ΅ Ссли ΠΌΠ΅Ρ‚ΠΎΠ΄ Π½Π΅ Π½Π°ΠΉΠ΄Π΅Π½ var body = Expression.Call(p, "SomeMethod", null); SomeMethodInvoker = Expression.Labmda<Action<T>>(body, p).Compile(); } void Foo(T a) { SomeMethodInvoker(a); } } 

But if you are too lazy to write so much code, you can use dynamic . Inside it has all the same construction of the expression and its compilation, only with add. checks:

 class SomeClass<T> { void Foo(T a) { ((dynamic)a).SomeMethod(); } }