Skip to content

Commit

Permalink
add support sealed records
Browse files Browse the repository at this point in the history
  • Loading branch information
Дмитрий authored and Дмитрий committed Sep 28, 2023
1 parent 1ab9810 commit e0204a6
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
33 changes: 33 additions & 0 deletions src/Mapster.Tests/WhenMappingRecordRegression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,28 @@ public void AdaptRecordStructToRecordStruct()
_structResult.X.ShouldBe(1000);
object.ReferenceEquals(_destinationStruct, _structResult).ShouldBeFalse();
}

[TestMethod]
public void AdaptToSealtedRecord()
{
var _sourceRecord = new TestRecord() { X = 2000 };
var _destinationSealtedRecord = new TestSealedRecord() { X = 3000 };
var _RecordResult = _sourceRecord.Adapt(_destinationSealtedRecord);

_RecordResult.X.ShouldBe(2000);
object.ReferenceEquals(_destinationSealtedRecord, _RecordResult).ShouldBeFalse();
}

[TestMethod]
public void AdaptToSealtedPositionalRecord()
{
var _sourceRecord = new TestRecord() { X = 2000 };
var _destinationSealtedPositionalRecord = new TestSealedRecordPositional(4000);
var _RecordResult = _sourceRecord.Adapt(_destinationSealtedPositionalRecord);

_RecordResult.X.ShouldBe(2000);
object.ReferenceEquals(_destinationSealtedPositionalRecord, _RecordResult).ShouldBeFalse();
}

[TestMethod]
public void AdaptRecordToClass()
Expand Down Expand Up @@ -361,5 +383,16 @@ record struct TestRecordStruct
public int X { set; get; }
}

/// <summary>
/// Different Checked Constructor Attribute From Spec
/// https://learn.microsoft.com/ru-ru/dotnet/csharp/language-reference/proposals/csharp-9.0/records#copy-and-clone-members
/// </summary>
sealed record TestSealedRecord()
{
public int X { get; set; }
}

sealed record TestSealedRecordPositional(int X);

#endregion TestClasses
}
2 changes: 1 addition & 1 deletion src/Mapster/Utils/ReflectionUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ public static bool IsRecordType(this Type type)
var ctors = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).ToList();

var isRecordTypeCtor = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)
.Where(x => x.IsFamily == true)
.Where(x => x.IsFamily == true || x.IsPrivate == true)
.Any(x => x.GetParameters()
.Any(y => y.ParameterType == type));

Expand Down

0 comments on commit e0204a6

Please sign in to comment.