I need to create instance of a generic class like this:
Type T = Type.GetType(className).GetMethod(functionName).ReturnType;
var comparer = new MyComparer<T>(); // ERROR: "The type or namespace name 'T' could not be found"
I found this answer where this is possible only with reflection. But using reflection I get object which I need to cast to my generic type. I tried like this
Type myGeneric = typeof(MyComparer<>);
Type constructedClass = myGeneric.MakeGenericType();
object created = Activator.CreateInstance(constructedClass);
var comparer = (T)Convert.ChangeType(created, T);// ERROR: "The type or namespace name 'T' could not be found"
but get the same error. How to solve it?
Here is a complete example:
public static bool Test(string className, string functionName, object[] parameters, object correctResult)
{
var method = Type.GetType(className).GetMethod(functionName);
Type T = method.ReturnType;
var myResult = method.Invoke(null, parameters);
dynamic myResultAsT = Convert.ChangeType(myResult, T);
dynamic correctResultAsT = Convert.ChangeType(correctResult, T);
var comparer = new MyComparer<T>(); // Problem is here!!!
return comparer.Equals(myResultAsT, correctResultAsT);
}
The idea is to make a unit test which will call a function with parameters and compare its result with the correct result. But I need custom comparer, so I implement MyComparer
which I cannot use because of a compiler error.
public class MyComparer<T> : IEqualityComparer<T>
{
public bool Equals(T x, T y){/* some implementation*/}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…