Skip to content

Commit 1b875b7

Browse files
Added custom exception for indexers being treated as properties during serialization (#885)
Mirrors #884 on the maintenance branch
1 parent c00f479 commit 1b875b7

File tree

3 files changed

+41
-1
lines changed

3 files changed

+41
-1
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
using System;
2+
using System.Reflection;
3+
4+
namespace MiniExcelLibs.Exceptions
5+
{
6+
public class MiniExcelNotSerializableException : InvalidOperationException
7+
{
8+
public MemberInfo Member { get; }
9+
10+
public MiniExcelNotSerializableException(string message, MemberInfo member) : base(message)
11+
{
12+
Member = member;
13+
}
14+
}
15+
}

src/MiniExcel/Reflection/Property.cs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
using System.Collections.Concurrent;
33
using System.Linq;
44
using System.Reflection;
5+
using MiniExcelLibs.Exceptions;
56

67
namespace MiniExcelLibs
78
{
@@ -18,7 +19,13 @@ public Property(PropertyInfo property)
1819
{
1920
Name = property.Name;
2021
Info = property;
21-
22+
23+
if (property.GetIndexParameters().Length != 0)
24+
{
25+
const string msg = "Types containing indexers cannot be serialized. Please remove them or decorate them with MiniExcelIgnoreAttribute.";
26+
throw new MiniExcelNotSerializableException(msg, property);
27+
}
28+
2229
if (property.CanRead)
2330
{
2431
CanRead = true;

tests/MiniExcelTests/MiniExcelIssueTests.cs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4719,4 +4719,22 @@ public void TestIssue876()
47194719
MiniExcel.SaveAs(outputPath.ToString(), sheets);
47204720
});
47214721
}
4722+
4723+
private class Issue880
4724+
{
4725+
public string Test { get; set; }
4726+
public string this[int i] => "";
4727+
}
4728+
4729+
[Fact]
4730+
public void TestIssue880_ShouldThrowNotSerializableException()
4731+
{
4732+
Issue880[] toExport = [new() { Test = "test" }];
4733+
4734+
Assert.Throws<MiniExcelNotSerializableException>(() =>
4735+
{
4736+
using var ms = new MemoryStream();
4737+
ms.SaveAs(toExport);
4738+
});
4739+
}
47224740
}

0 commit comments

Comments
 (0)