2011-01-30 3 views
0

사전 (또는 다른 이름 - 값 컬렉션)에서 속성을 매핑 할 수있는 개체 개체 매퍼가 있습니까?Dictionary <string, object> from object mapper

의 나는 내가하고 싶은 어떤 클래스

public class SomeClass 
{ 
    public string Text { get; set; } 
    public Address HomeAddress { get; set; } 
    public List<int> Numbers { get; set; } 
} 
public class Address 
{ 
    public string Street { get; set; } 
    public string PostalCode { get; set; } 
    public string City { get; set; }  
} 

가 있다고 가정하자 상황 및 메타 데이터 관련이 많이 필요합니다 ASP.NET MVC에서 DefaultModelBinder처럼 기본적이다

var values = new Dictionary<string,object>(); 
values.Add("Text","Foo"); 
values.Add("HomeAddress.Street","Some street 123"); 
values.Add("HomeAddress.PostalCode","12345"); 
values.Add("HomeAddress.City","Some city"); 
values.Add("Numbers[0]",123); 
values.Add("Numbers[1]",234); 
values.Add("Numbers[2]",345); 

SomeClass some = aMapperTool.CreateFromDictionary<SomeClass>(values); 

입니다 따라서 매우 편리하지 않습니다.

+0

확인 [이] (http://samarskyy.blogspot.com/2011/02/net- 유래의 다른 곳에서 해결되었습니다합니다 (ComponentModel 기능을 활용할 수 있습니다 customizing-automatic-mappings.html) out. – AlexBar

답변

0

반사 또는 표현 트리를 사용하지 않아도됩니다. 반사와

, 그것은 다음과 같은 대략 다음과 같습니다 필요한 경우

  1. 이 (HomeAddress.Street에서 실제 속성 이름을 구성, details에 키를 통해 T
  2. 으로 반복의 객체를 생성 ->HomeAdress 또는 Numbers[0] ->Number). 속성의 유형에 따라 (.을 찾을 경우 [을 찾으면 자식 객체를 먼저 생성해야하며 IEnumerable을 초기화해야합니다.)
  3. 하위 구조를 생성 한 후 상위 개체를 구성하십시오.

이것은 가능한 해결책이지만 내 머리를 통과하는 질문이 하나 있습니다. "왜?"

+0

추한 xml없이 하나의 데이터베이스 테이블이나 텍스트 파일에 poco 객체를 저장하고 "where name = 'foo'및 value = 'bar'를 검색하는 것이 좋습니다. " –

+0

그런 다음 POCO 저장 /로드를위한 사용자 지정 래퍼와 함께 sqlite를 사용하는 것이 좋습니다. 작업은 끔찍하며 특히 "데이터베이스"에 자주 액세스하는 경우 엄청난 양의 응용 프로그램 성능에 부정적인 영향을 미칩니다. – Femaref

1

이이

how to set nullable type via reflection code (c#)?

using System.ComponentModel; 

public void FillMeUp(Dictionary<string, string> inputValues){ 

     PropertyInfo[] classProperties = this.GetType().GetProperties(); 

     var properties = TypeDescriptor.GetProperties(this); 

     foreach (PropertyDescriptor property in properties) 
     { 
      if (inputValues.ContainsKey(property.Name)) 
      { 
       var value = inputValues[property.Name]; 
       property.SetValue(this, 
           property.Converter.ConvertFromInvariantString(value)); 
      } 
     } 
관련 문제