2012-06-26 74 views
1


我在嘗試將object映射到int時遇到了一些麻煩。
我的類和方法,其中轉換:發送映射器。將對象轉換爲int

[Serializable] 
public class ProfileProperty 
{ 
    public object PropertyValue { get; set; } 

    public bool IsVisible { get; set; } 

    public ProfileProperty(object value, bool isVisible = true) 
    { 
     this.PropertyValue = value; 
     this.IsVisible = isVisible; 
    } 

    public ProfileProperty() 
    { 
     this.IsVisible = true; 
    } 

    public T GetValue<T>() 
    { 
     return (T)this.PropertyValue; 
    } 

    public override string ToString() 
    { 
     if (this.PropertyValue != null) 
     { 
      return this.PropertyValue.ToString(); 
     } 

     return string.Empty; 
    } 
} 

[Serializable] 
public class ProfileProperty 
{ 
    public object PropertyValue { get; set; } 

    public bool IsVisible { get; set; } 

    public ProfileProperty(object value, bool isVisible = true) 
    { 
     this.PropertyValue = value; 
     this.IsVisible = isVisible; 
    } 

    public ProfileProperty() 
    { 
     this.IsVisible = true; 
    } 

    public T GetValue<T>() 
    { 
     return (T)this.PropertyValue; 
    } 

    public override string ToString() 
    { 
     if (this.PropertyValue != null) 
     { 
      return this.PropertyValue.ToString(); 
     } 

     return string.Empty; 
    } 
} 

public static class Helper 
{ 
    public static ProfileModel PopulProfMod(Profile profile) 
    { 
     var mapper = ObjectMapperManager.DefaultInstance.GetMapper<Profile, ProfileModel>(new DefaultMapConfig() 
        .IgnoreMembers<Profile, ProfileModel>(new string[] { "GetValue", "ToString" })); 
     ProfileModel prof = new ProfileModel(); 
     if (profile != null) 
     { 
      prof = mapper.Map(profile); 
      //prof.Age = (int)profile.Age.PropertyValue; 
      prof.Visibility = new List<string>(); 
     } 

     //Some code 

     return prof; 
    } 
} 

當對應的屬性Age是0,但profile

Profile profile = new Profile() 
      { 
       Age = new ProfileProperty() { IsVisible = true, PropertyValue = 17 }, 
       Comments = 2, 
       UserName = "Luck", 
       FirstName = new ProfileProperty() { IsVisible = false, PropertyValue = "Alex" } 
      }; 

回答

0

你需要一個轉換器:

new DefaultMapConfig() 
     .IgnoreMembers<Profile, ProfileModel>(new string[] { "GetValue", "ToString" })) 
     .ConvertUsing<ProfileProperty, int>(s => (int)s.PropertyValue)