2012-02-16 34 views
1

如果我有這樣的字符串列表:怎麼投這個字符串列表對象

其中
string myObjectString = "MyObject, SetWidth, int, 10, 0, 1"; 

- MyObject: the object class 
- SetWidth: the property of the object 
- int: type of the SetWidth is int 
- 10: default value 
- 0: object order 
- 1: property order 

那我該怎麼構建這樣一個對象:

[ObjectOrder(0)] 
public class MyObject: 
{ 
    private int _SetWidth = 10; 

    [PropertyOrder(1)] 
    public int SetWidth 
    { 
     set{_SetWidth=value;} 
     get{return _SetWidth;} 
    } 
} 

所以,我想有這樣的事情:

Object myObject = ConstructAnObject(myObjectString); 

myObjectMyObject的實例。在C#中可能嗎?

在此先感謝。

+2

等等......你想要既生成類又實例化它的一個實例嗎?或者你已經定義了類,並且你想實例化一個實例? – Jamiec 2012-02-16 10:16:54

回答

2

下面是一些快速和骯髒的代碼,讓你開始:

 string myObjectString = "MyObject, SetWidth, int, 10, 0, 1"; 
     var info = myObjectString.Split(','); 

     string objectName = info[0].Trim(); 
     string propertyName = info[1].Trim(); 
     string defaultValue = info[3].Trim(); 

     //find the type 
     Type objectType = Assembly.GetExecutingAssembly().GetTypes().Where(t=>t.Name.EndsWith(objectName)).Single();//might want to redirect to proper assembly 

     //create an instance 
     object theObject = Activator.CreateInstance(objectType); 

     //set the property 
     PropertyInfo pi = objectType.GetProperty(propertyName); 
     object valueToBeSet = Convert.ChangeType(defaultValue, pi.PropertyType); 
     pi.SetValue(theObject, valueToBeSet, null); 

     return theObject; 

這將找到MyObject,創建適當的屬性類型的對象,並設置匹配屬性。

+0

這看起來不錯,我該如何添加:[ObjectOrder(0)]和[PropertyOrder(1)]?提前致謝。 – olidev 2012-02-16 11:58:14

+0

我不確定,據我所知,屬性是在類型上定義的,而不是在單個實例上定義的。 – 2012-02-16 12:24:39

1

假設你需要生成新類型有兩種可能的方式:

  1. 使用Reflection Emit
  2. 使用CodeDom provider

我認爲更簡單的解決方案是CodeDom提供程序。所有需要的是以內存中的字符串形式生成源代碼,然後編譯代碼並使用Activator實例化新實例。這是一個不錯的example我剛剛找到。
我認爲CodeDom提供程序更簡單的原因是它具有較短的設置 - 無需生成動態模塊和程序集,然後使用類型生成器和成員構建器。另外,它不需要與IL一起工作來產生吸氣和吸氣體。
反射發出的優點是性能 - 即使在使用其中一種類型後,動態模塊也可以爲自身添加更多類型。 CodeDom提供者需要一次創建所有類型,否則每次創建一個新程序集。

1

如果您使用C#4.0,則可以使用新的dynamic功能。

string myObjectString = "MyObject, SetWidth, int, 10, 0, 1"; 
String[] properties = myObjectString.Split(','); 
dynamic myObj; 

myObj.MyObject = (objtect)properties[0]; 
myObj.SetWidth = Int32.Parse(properties[1]); 

// cast dynamic to your object. Exception may be thrown. 

MyObject result = (MyObject)myObj; 
+0

與此聲明:動態myObj,我想我不能這樣做:myObj.MyObject。如果我聲明:dynamic myObj = new object();那麼我不能做myObj.MyObject =(object)屬性[0] – olidev 2012-02-16 10:42:09

+0

你是對的。關鍵是使用'dynamic'來解決它。 – 2012-02-17 01:38:40

1

我不明白爲什麼你需要ObjectOrder和PropertyOrder ......一旦你有他們的名字你可能並不需要它們,至少在「反序列化」 ......

或者請指教他們的作用是什麼?

你絕對可以簡單地通過反射做到這一點:

  • 分割字符串用逗號(使用mystring。分裂)
  • 使用反射來找到你的應用程序內的對象:
    • 找到與名稱類型= splittedString [0](枚舉域內的所有組件和每個組件中的所有類型的);
    • 實例化(使用Activator.CreateInstance)中發現的類型
  • 查找名稱的屬性(使用objectType.GetProperty)
  • 設置(使用propertyInfo.SetValue)
  • 返回對象的屬性值
相關問題