Shared class instance with type from PropertyInfo.PropertyType

I have classes as below:

public class SampleClassToTest<T> { public static Fake<T> SomeMethod(string parameter) { // some code } public static Fake<T> SomeMethod(string parameter, int anotherParameter) { //some another code } } public class Fake<T> { // some code } 

And I want to use them as follows:

 SampleClassToTest<MyClass>.SomeMethod("some parameter"); 

The problem I have is this: the type is "MyClass", which I can only get from the PropertyInfo instance using Reflection, so I have

 Type propertyType = propertyInfo.PropertyType; 

How can i do this? Any ideas?

UPD I am trying to pass a type to a generic method. And yes, that is what I want.

+4
source share
2 answers

You will need to do:

 typeof(SampleClassToTest<>).MakeGenericType(propertyType) .GetMethod("SomeMethod", new Type[] {typeof(string)}) .Invoke(null, new object[] {"some parameter"}); 

Nasty.

If that helps at all, I would suggest offering a non-generic API that accepts an instance of Type ; that a generic API can trivially call a non-standard API using typeof(T) .

+3
source

It looks like you want:

 Type propertyType; Type classType = typeof(SampleClassToTest<>).MakeGenericType(propertyType); MethodInfo method = classType.GetMethod("SomeMethod", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(string) }, null); object fake = method.Invoke(null, new object[] { "some parameter" }); 
+2
source

Source: https://habr.com/ru/post/1469506/


All Articles