【问题标题】:Emit mapper. Convert object to int发射映射器。将对象转换为 int
【发布时间】:2012-06-26 13:23:09
【问题描述】:


当我尝试将object 映射到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" }
            };

【问题讨论】:

    标签: c# .net emitmapper


    【解决方案1】:

    你需要一个转换器:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-12
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      • 2013-05-30
      • 1970-01-01
      相关资源
      最近更新 更多