C# 泛型和反射——将对象传递给泛型方法

C# Generics and Reflection - Passing an object to a generic method

我有一个具有以下签名的方法:

    private string SerialiazeObj<T>(T obj)
    {
          // Do some work
    }

现在,我有另一个方法接受对象并调用 SerializeObj 方法,如下所示:

    private void callSerializeObj(object obj)
    {
        Type objType = obj.GetType();
        string s = SerialiazeObj<objType>((objType)obj));
    }

传递给 callSerializeObj 的对象可以是任何类型。不幸的是,编译器在 (string s = SerializeObj...) 部分给我这个错误:

The type or namespace 'objType' could not be found (are you missing an assembly reference).

我不知道我是否以正确的方式调用 SerializeObj。使用可以是任何类型的对象调用方法的正确方法是什么?

使用如下-

private void callSerializeObj(object obj)
    {
        Type objType = obj.GetType();

       MethodInfo method = this.GetType().GetMethod("SerialiazeObj", BindingFlags.NonPublic | BindingFlags.Instance);
       MethodInfo generic = method.MakeGenericMethod(objType );
       object Result = generic.Invoke(this, new object[] { obj });
    }