重写类型转换

This commit is contained in:
falcon 2022-07-14 09:01:38 +08:00
parent 6430a50bdf
commit 1a5da57187
2 changed files with 31 additions and 1 deletions

View File

@ -33,6 +33,14 @@ namespace Falcon.SugarApi.Test
Assert.IsTrue(t.ica.ItemA == "itema");
Assert.IsTrue(t.ica.Equals(s.ica));
}
[TestMethod]
public void ChangeTypeTest() {
int s = 1;
var t = s.ChangeType(typeof(int));
Console.WriteLine(t.GetType().FullName);
Assert.IsTrue(t.GetType().Equals(typeof(int)));
}
}
public class SourceClass

View File

@ -1,4 +1,5 @@
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
@ -22,7 +23,8 @@ namespace Falcon.SugarApi
join t in target.GetType().GetProperties() on s.Name equals t.Name
select new { s, t };
foreach (var item in all) {
item.t.SetValue(target, Convert.ChangeType(item.s.GetValue(source), item.t.PropertyType));
//item.t.SetValue(target, Convert.ChangeType(item.s.GetValue(source), item.t.PropertyType));
item.t.SetValue(target,item.s.GetValue(source).ChangeType(item.t.PropertyType));
}
return source;
}
@ -38,5 +40,25 @@ namespace Falcon.SugarApi
source.CloneTo(target);
return target;
}
/// <summary>
/// 将对象转换成另一类型如果转换失败可能返回null。
/// </summary>
/// <param name="source">原对象</param>
/// <param name="targetType">目标类型</param>
/// <returns>转换后的类型</returns>
public static object? ChangeType(this object? source,Type targetType) {
if (targetType == null) {
throw new ArgumentNullException("targetType");
}
if (source==null) {
return null;
}
if (targetType.IsGenericType && targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) {
NullableConverter nullableConverter = new NullableConverter(targetType);
targetType = nullableConverter.UnderlyingType;
}
return Convert.ChangeType(source, targetType);
}
}
}