调用在c#泛型类中定义的泛型参数的泛型方法



下面是我的代码:

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";
}

我想调用一个泛型方法,在运行时在泛型类中定义泛型参数但是我得到了异常

"系统。ArgumentException: " " TestPlatformApi. "MyRequest ' Genericarguments [0] on 1 [t] "gettidrequest "类型'"违反约束

  1. 正如Charlieface评论的那样,你应该删除MyRequest上的约束。
  2. 从你的代码,我不能得到你的设计足够。因此,我在假设。下面显示一些代码
public class MyClass<T> where T : MsgConstraint
{
private IList<T> middlewares = new List<T>();
public void Register(T m)
{
middlewares.Add(m);
}
public T DoRequest(Type type)
{
return middlewares.Where(st => st.GetType() == type).FirstOrDefault();
}
}
public interface MsgConstraint
{
public string Msg { set; get; }
}
public class HttpMsg : MsgConstraint
{
public string Msg { get; set; } = "HTTPMSG";
}
public class RpcMsg : MsgConstraint
{
public string Msg { get; set; } = "RPCMSG";
}
class Program
{
static void Main(string[] args)
{
MyClass<MsgConstraint> myClass = new MyClass<MsgConstraint>();
myClass.Register(new HttpMsg());
myClass.Register(new RpcMsg());
MsgConstraint http = myClass.DoRequest(typeof(HttpMsg));
Console.WriteLine(http.Msg);
MsgConstraint rpc = myClass.DoRequest(typeof(RpcMsg));
Console.WriteLine(rpc.Msg);
}
}

相关内容

  • 没有找到相关文章

最新更新