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

标签 c# .net reflection

我在 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,这意味着 XmlSerser 实例无法获得 的类型测试类(结果为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/

相关文章:

.net - 如何在另一个项目中托管一个项目的 WCF 服务?

java - 用接受字符串参数的构造函数实例化一个类对象?

php - 在 Yii2 中在运行时声明类属性

c# - 使用 Protobuf-net 和 Monotouch for IOS 通过 WCF 序列化 IEnumerable

c# - 如何在运行时更改 EasingDoubleKeyFrame 值?

.net - 在 .NET 中使用 MySQL GeoSpatial 数据类型

具有通用类类型的 Java 反射 getDeclaredMethod()

c# - 使用 PIA 执行宏后锁定 Word 文档

C# ToString ("MM/dd/yy") 删除前导 0

c# - 您能否以编程方式检测 Excel 文档中的文本颜色并仅修改具有特定颜色和字体样式的文本的单元格?