2013-01-11 18 views
0

可能重複:
Create class instance in assembly from string name轉換爲類型T,其中我有T的字符串名稱

使用類型MyClass我想從創建MyClass實例的字符串表示它的字符串表示。

查看評論在我的代碼:

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; 
     } 
    } 
} 
+0

的可能重複[創建從字符串名裝配類實例(http://stackoverflow.com/questions/12433451/create-class-instance-in-assembly-from-string -name)或http://stackoverflow.com/questions/648160/或http://stackoverflow.com/questions/223952/c-sharp-create-an-instance-of-a-class-from-a-string等等等等 –

+0

這個怎麼樣: http://stackoverflow.com/questions/1044455/c-sharp-reflection-how-to-get-class-reference-from-string – JLRishe

回答

0

你應該瞭解Serialization

要將您的班級數據保存到字符串,您應該將序列化爲您的MyClass對象爲字符串。 要從字符串中檢索您的班級數據,您應該反序列化您的MyClass對象來自字符串。

XmlSerializer將幫助您

+0

使用此肯定會比意味着只有一個C#應用程序可以訪問它。 – Cheetah

+0

@Ben,no。您可以將反序列化的對象存儲在文件中。 Java應用程序可以讀取此文件並在其自己的類中反序列化,類似於「MyClass」。 –

相關問題