here is my code:
class Program1
{
private static void Main(string[] args)
{
//MyClass myClass = new MyClass();
//GetIdRequest getIdRequest = new GetIdRequest();
//GetIdReponse getIdReponse= myClass.DoRequest(getIdRequest);
//Console.WriteLine($"getIdReponse.Msg:" + getIdReponse.Msg + ",getIdReponse.Data:" + getIdReponse.Data);
Type myClassType = typeof(MyClass);
Object myClassTypeInstance = System.Activator.CreateInstance(myClassType);
Type unboundGenericType = typeof(MyRequest<>);
Type boundGenericType = unboundGenericType.MakeGenericType(typeof(GetIdRequest));
Type getIdRequestType = typeof(GetIdRequest);
Object getIdRequest = System.Activator.CreateInstance(getIdRequestType);
MethodInfo methodInfo = myClassType.GetMethod("DoRequest", BindingFlags.Public| BindingFlags.Instance, null, new Type[] { boundGenericType }, null);
object res = methodInfo.Invoke(myClassTypeInstance, new object[] { getIdRequest });
Console.ReadKey();
}
}
public class MyClass
{
public T DoRequest<T>(MyRequest<T> obj) where T : MyReponse
{
T res = Activator.CreateInstance<T>();
return res;
}
}
public class GetIdRequest: MyRequest<GetIdReponse>
{
}
public class GetIdReponse: MyReponse
{
public string Data { set; get; } = "data";
}
public interface MyRequest<T> where T: MyReponse
{
}
public class MyReponse
{
public string Msg { set; get; } = "res";
}
i want to Invoke a generic method with generic arguments defined in a generic class by runtime
but i get the Exception
"System.ArgumentException :““ TestPlatformApi.MyRequest `Genericarguments [0] on 1 [t] "“ TestPlatformApi.GetIdRequest ”Violation of constraint on type't'"
question from:
https://stackoverflow.com/questions/65894905/invoke-a-generic-method-with-generic-arguments-defined-in-a-generic-class-in-c-s 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…