C#从Generic方法调用Generic方法

Ily*_*lya 1 c# generics

我怎么能做这样的事情?我发现如何使用反射来调用泛型方法?但不确定这是我的情况.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Den*_*nis 8

调用另一个泛型方法的泛型方法不能比被调用的方法更少受约束:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

这里Bar4方法中断了Bar1约束,因为它允许您将值类型作为泛型参数传递,但这不允许用于Bar1方法.