【问题标题】:Cast to type T where I have the string name of T [duplicate]转换为类型 T 我有 T 的字符串名称 [重复]
【发布时间】:2013-01-12 01:16:56
【问题描述】:

可能重复:
Create class instance in assembly from string name

使用MyClass 类型的字符串表示我想从它的字符串表示中创建MyClass 的实例。

查看我的代码中的 cmets:

interface MyData
{
    string Value { get; }
}

class MyClass : MyData
{
    public MyClass(string s)
    {
        Value = s;
    }

    public string Value { get; private set; }

    public static explicit operator MyClass(string strRep)
    {
        return new MyClass(strRep);
    }

    public static implicit operator string(MyClass inst)
    {
        return inst.Value;
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyClass inst = new MyClass("Hello World");

        string instStr = inst; //string representation of MyClass
        string instTypeStr = inst.GetType().FullName;

        // I want to be able to do this:
        MyData copyInst = (instTypeStr)instStr; // this would throw an error if instTypeStr did not inherit MyData

        // Then eventually:
        if (instTypeStr.Equals("MyClass"))
        {
            MyClass = (MyClass)copyInst;
        }
    }
}

【问题讨论】:

标签: c# reflection


【解决方案1】:

你可以使用Activator.CreateInstance方法

链接:http://msdn.microsoft.com/fr-fr/library/d133hta4(v=vs.80).aspx

【讨论】:

    【解决方案2】:

    你应该了解Serialization

    要将您的类数据保存为字符串,您应该序列化您的MyClass 对象为字符串。 要从字符串中检索您的类数据,您应该从字符串中反序列化您的MyClass 对象。

    XmlSerializer 会帮助你

    【讨论】:

    • 使用它肯定意味着只有 C# 应用程序可以访问它。
    • @Ben,不。您可以将反序列化的对象存储在文件中。 Java应用程序可以读取这个文件并在自己的类中反序列化,类似于MyClass
    猜你喜欢
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多