From 47fb5961a3da1c6af784ea08f488372d5f05ab57 Mon Sep 17 00:00:00 2001 From: Michele Bastione Date: Tue, 7 Oct 2025 22:27:29 +0200 Subject: [PATCH] Added custom exception for indexers being treated as properties during serialization --- .../MiniExcelNotSerializableException.cs | 7 +++++++ .../Reflection/MiniExcelProperty.cs | 8 ++++++++ .../MiniExcelIssueTests.cs | 18 ++++++++++++++++++ 3 files changed, 33 insertions(+) create mode 100644 src/MiniExcel.Core/Exceptions/MiniExcelNotSerializableException.cs diff --git a/src/MiniExcel.Core/Exceptions/MiniExcelNotSerializableException.cs b/src/MiniExcel.Core/Exceptions/MiniExcelNotSerializableException.cs new file mode 100644 index 00000000..7440bb13 --- /dev/null +++ b/src/MiniExcel.Core/Exceptions/MiniExcelNotSerializableException.cs @@ -0,0 +1,7 @@ +namespace MiniExcelLib.Core.Exceptions; + +public class MiniExcelNotSerializableException(string message, MemberInfo member) + : InvalidOperationException(message) +{ + public MemberInfo Member { get; } = member; +} \ No newline at end of file diff --git a/src/MiniExcel.Core/Reflection/MiniExcelProperty.cs b/src/MiniExcel.Core/Reflection/MiniExcelProperty.cs index 3c2dafe7..cd1c5fa5 100644 --- a/src/MiniExcel.Core/Reflection/MiniExcelProperty.cs +++ b/src/MiniExcel.Core/Reflection/MiniExcelProperty.cs @@ -1,3 +1,5 @@ +using MiniExcelLib.Core.Exceptions; + namespace MiniExcelLib.Core.Reflection; public abstract class Member; @@ -12,6 +14,12 @@ public MiniExcelProperty(PropertyInfo property) Name = property.Name; Info = property; + if (property.GetIndexParameters().Length != 0) + { + const string msg = "Types containing indexers cannot be serialized. Please remove them or decorate them with MiniExcelIgnoreAttribute."; + throw new MiniExcelNotSerializableException(msg, property); + } + if (property.CanRead) { CanRead = true; diff --git a/tests/MiniExcel.Core.Tests/MiniExcelIssueTests.cs b/tests/MiniExcel.Core.Tests/MiniExcelIssueTests.cs index d48ccb9c..9e22e35e 100644 --- a/tests/MiniExcel.Core.Tests/MiniExcelIssueTests.cs +++ b/tests/MiniExcel.Core.Tests/MiniExcelIssueTests.cs @@ -3710,4 +3710,22 @@ public void TestIssue876() _excelExporter.Export(outputPath.ToString(), sheets); }); } + + private class Issue880 + { + public string Test { get; set; } + public string this[int i] => ""; + } + + [Fact] + public void TestIssue880_ShouldThrowNotSerializableException() + { + Issue880[] toExport = [new() { Test = "test" }]; + + Assert.Throws(() => + { + using var ms = new MemoryStream(); + _excelExporter.Export(ms, toExport); + }); + } } \ No newline at end of file