亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用反射映射相似對象:對象與目標類型不匹配

使用反射映射相似對象:對象與目標類型不匹配

PHP
肥皂起泡泡 2021-06-11 15:09:59
盡管查看了多個 SO 帖子和我能想到的任何其他內容,但我在這里完全不知所措。我的目標是制作一個非常非常簡單的映射器。我基本上可以在某些單元測試中用作工具的東西。它不需要很復雜或任何東西——只需將一個對象的高級原始值和字符串值映射到另一個對象。所以基本算法是:獲取所有屬性 TFrom獲取所有屬性 TTo獲取兩者中的所有屬性,按名稱匹配。我知道這可能是一個錯誤,因為它們可能具有相同的名稱但類型不同,但讓我們把它放在一邊。這不是我在這里遇到的問題——屬性和類型在類之間匹配。創建一個TTo我們可以復制到的實例。對于在對象之間映射的每個屬性:獲取from對象的值將值轉換為屬性的類型在to對象上設置值問題是,無論我做什么,無論屬性的類型是什么(int或者string,例如),我都會得到以下信息:對象與目標類型不匹配。這是我正在使用的代碼:public TTo Map<TFrom, TTo>(TFrom from){    if (from == null) return default;    var fromProps = GetProperties(typeof(TFrom));    var toProps = GetProperties(typeof(TTo));    // Props that can be mapped from one to the other    var propsToCopy = fromProps.Intersect(toProps, new PropertyComparer()).ToList();    var returnObject = (TTo)Activator.CreateInstance(typeof(TTo));    foreach (var prop in propsToCopy)    {        // Copy the values        var fromValue = prop.GetValue(from, null);        var convertedValue = Convert.ChangeType(fromValue, prop.PropertyType);        prop.SetValue(returnObject, convertedValue, null);    }    return returnObject;}public PropertyInfo[] GetProperties(Type objectType){    var allProps = objectType.GetProperties(        BindingFlags.Public | BindingFlags.Instance);    return allProps.Where(p => p.PropertyType.IsPrimitive ||        p.PropertyType == typeof(string)).ToArray();}private class PropertyComparer : IEqualityComparer<PropertyInfo>{    public bool Equals(PropertyInfo x, PropertyInfo y)    {        return x.Name.Equals(y.Name);    }    public int GetHashCode(PropertyInfo obj)    {        return obj.Name.GetHashCode();    }}這是我將其稱為示例類的示例:public class Foo {    public string StringProp { get; set; }    public int IntProp { get; set; }}public class FooOther{    public string StringProp { get; set; }    public int IntProp { get; set; }}var foo = new Foo { IntProp = 1, StringProp = "foo" };var mappedFoo = Map<Foo, FooOther>(foo);我從 Visual Studio 中得到的唯一提示來自監視窗口:如果屬性類型是 a string,監視窗口報告的類型為convertedValueas object。如果屬性類型是int,監視窗口會報告object {int}。
查看完整描述

1 回答

  • 1 回答
  • 0 關注
  • 558 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號