Question

I have classes like 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 in this way:

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

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

Type propertyType = propertyInfo.PropertyType;

How can I do this? Any ideas?

UPD. I'm trying to pass the Type to generic method. And yes, this is what I want.

Was it helpful?

Solution

You would need to do:

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

Ugly.

If it can at all be helped, I would advise offering a non-generic API that accepts a Type instance; the nice thing here is that a generic API can call into a non-generic API trivially by using typeof(T).

OTHER TIPS

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" });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top