c#:在exe类型字符串上从dll调用Type.GetType

ale*_*oat 2 .net c# reflection

我在XmlSer.dll中有以下类

namespace xmlser
{
        public class XmlSer
        {
                public Type test(string s)
                {
                    return Type.GetType(s);
                }

        //...other code

        }
}
Run Code Online (Sandbox Code Playgroud)

以及MyApp.exe中的以下代码,它将XmlSer.dll作为参考链接

namespace MyApp
{
    public class TestClass
    {
        public int f1 = 1;
        public float f2 = 2.34f;
        public double f3 = 3.14;
        public string f4 = "ciao";
    }

    class MainClass
    {

        public static void Main(string[] args)
        {
            TestClass tc = new TestClass();
            XmlSer ser = new XmlSer();
            Console.WriteLine(ser.test("MyApp.TestClass")!=null);
        }
}
Run Code Online (Sandbox Code Playgroud)

运行MyApp.exe我得到false,这意味着XmlSer的ser实例无法获取Testclass的类型(结果为null).将XmlSer类直接放在MyApp.exe代码中我正确地获得了TestClass的类型.

检查网络我发现问题与程序集有关.这意味着,.exe的程序集对XmlSer.test方法不可见,因此无法解析TestClass的类型.

如何解决在MyApp.exe中维护XmlSer.dllMyApp.MainClass中的XmlSer的问题

谢谢.

亚历山德罗

Joh*_*ers 6

由于这两个不在同一个程序集中,您可能需要在类型字符串中包含程序集名称:

Console.WriteLine(ser.test("MyApp.TestClass, MyApp")!=null);
Run Code Online (Sandbox Code Playgroud)

如果您只想序列化任意对象,则可以执行以下操作:

public static class Serialization
{
    public static void Serialize(object o, Stream output)
    {
        var serializer = new XmlSerializer(o.GetType());
        serializer.Serialize(output, o);
    }
}
Run Code Online (Sandbox Code Playgroud)