我在 XmlSer.dll 中有以下类
namespace xmlser
{
public class XmlSer
{
public Type test(string s)
{
return Type.GetType(s);
}
//...other code
}
}
以及 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);
}
}
运行 MyApp.exe 我得到 false,这意味着 XmlSer 的 ser 实例无法获得 的类型测试类(结果为null)。 将 XmlSer 类直接放入 MyApp.exe 代码中,我正确地获得了 TestClass 的类型。
在网上查了一下,我发现问题与程序集有关。这意味着,.exe 的程序集对 XmlSer.test 方法不可见,因此它无法解析 TestClass 的类型。
如何解决在 XmlSer.dll 中维护 XmlSer 和在 MyApp.exe 中维护 MyApp.MainClass 的问题> ?
谢谢。
亚历山德罗
最佳答案
由于两者不在同一个程序集中,您可能需要在类型字符串中包含程序集名称:
Console.WriteLine(ser.test("MyApp.TestClass, MyApp")!=null);
如果您只想序列化任意对象,您可以执行以下操作:
public static class Serialization
{
public static void Serialize(object o, Stream output)
{
var serializer = new XmlSerializer(o.GetType());
serializer.Serialize(output, o);
}
}
关于c# : Type. 从 exe 类型字符串上的 dll 调用的 GetType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/629666/