Is there any way to make this code:
class GenericClass<T> { void functionA() { T.A(); } }
Or how to call the type parameter function (type is my own class).
To call an object method of a generic type, you must first create it.
public static void RunSnippet() { var c = new GenericClass<SomeType>(); } public class GenericClass<T> where T : SomeType, new() { public GenericClass(){ (new T()).functionA(); } } public class SomeType { public void functionA() { //do something here Console.WriteLine("I wrote this"); } }
Re:
T.A();
You cannot call static methods of a type parameter if that is what you mean. You would be better off reorganizing this as an instance method T, perhaps with a common constraint ( where T : SomeTypeOrInterface, with SomeTypeOrInterface, defining A()). Another alternative is dynamicthat allows duck typing of instance methods (via signature).
T
where T : SomeTypeOrInterface
SomeTypeOrInterface
A()
dynamic
, T ( Type), :
Type
typeof(GenericClass<>).MakeGenericType(type).GetMethod(...).Invoke(...);
, :
class GenericClass<T> where T : MyBaseClass { void functionA<T>(T something) { something.A(); } }
, , - T, functionA. , , , T A, .
functionA
A
, , .
. :