[英]C# Call Generic method from Generic method
How I can do something like this? 我该怎么做? I have found How do I use reflection to call a generic method?
我发现了如何使用反射来调用泛型方法? but not sure that this is my case.
但不确定这是我的情况。
public class XmlSerializer
{
public string Serialize<T>(T obj) where T : class
{
return string.Empty;
}
}
class Program
{
static void Main(string[] args)
{
MakeRequst<string>("value");
}
public static void MakeRequst<T>(T myObject)
{
var XmlSerializer = new XmlSerializer();
XmlSerializer.Serialize<T>(myObject);
}
}
Generic method, that calls another generic method, can't be less constrained, than the method being called: 泛型方法,它调用了另一个泛型方法,其约束比被调用的方法要少:
public class Foo
{
public void Bar1<T>() where T : class {}
public void Bar2<T>() where T : class
{
Bar1<T>(); // same constraints, it's OK
}
public void Bar3<T>() where T : class, ISomeInterface
{
Bar1<T>(); // more constraints, it's OK too
}
public void Bar4<T>()
{
Bar1<T>(); // less constraints, error
}
}
Here Bar4
method breaks Bar1
constraints, because it allows you to pass value type as generic argument, but this is not allowed for Bar1
method. 这里
Bar4
方法打破Bar1
的约束,因为它允许你传递值类型为通用的说法,但这是不允许的Bar1
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.