2011-12-03 5 views
11

내가이동적 개체에 동적으로 속성을 추가 하시겠습니까?

dynamic d = new ExpandoObject(); 
d.Name = attribute.QualifiedName.Name; 

그래서, 내가 d는 속성 이름있을 것이라는 점을 알고있다. 이제 내가 컴파일 타임에 속성의 이름을 모른다면 어떻게 그 속성을 동적으로 추가 할 수 있습니까? 나는 이것을 찾았다 SO Question

그래서, 전화 binders 등등의이 복잡한 개념이있다. 이것을하는 것은 처음부터 힘들다. 이것을하는 더 쉬운 방법?

+0

[에 (디자인 타임) 속성을 알 수없는 추가의 중복 가능성 ExpandoObject] (http://stackoverflow.com/questions/2974008/adding-unknown-at-design-time-properties-to-an-expandoobject) – nawfal

답변

23
dynamic d = new ExpandoObject(); 
((IDictionary<string,object>)d)["test"] = 1; 
//now you have d.test = 1 
4

당신은 또한 다음과 같이 할 수 있습니다 : -

여기
Dictionary<string,object> coll = new Dictionary<string,object>(); 
    coll.Add("Prop1","hello"); 
    coll.Add("Prop2",1); 
    System.Dynamic.ExpandoObject obj = dic.Expando(); 

//You can have this ext method to better help 

public static ExpandoObject Expando(this IEnumerable<KeyValuePair<string, object>> 
dictionary) 
     { 
      var expando = new ExpandoObject(); 
      var expandoDic = (IDictionary<string, object>)expando; 
      foreach (var item in dictionary) 
      { 
       expandoDic.Add(item); 
      } 
      return expando; 
     } 
+0

좋은 길 ... 훨씬 더 청결한 .. –

5

는 깨끗한 방법

var myObject = new ExpandoObject() as IDictionary<string, Object>;myObject.Add("Country", "Ireland");

관련 문제