Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/BootstrapBlazor/Extensions/ObjectExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,11 @@ internal static void Clone<TModel>(this TModel source, TModel item)
/// <returns>An instance of the specified type with initialized properties.</returns>
public static TItem? CreateInstance<TItem>(bool isAutoInitializeModelProperty = false)
{
if(typeof(TItem).IsInterface)
{
return default;
}
Comment on lines +249 to +252
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (bug_risk): Consider handling abstract classes similarly to interfaces.

Abstract classes cannot be instantiated either; consider checking typeof(TItem).IsAbstract to prevent runtime exceptions.

Suggested change
if(typeof(TItem).IsInterface)
{
return default;
}
if(typeof(TItem).IsInterface || typeof(TItem).IsAbstract)
{
return default;
}


var instance = Activator.CreateInstance<TItem>();
if (isAutoInitializeModelProperty)
{
Expand Down
8 changes: 8 additions & 0 deletions test/UnitTest/Extensions/ObjectExtensionsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,14 @@ public void CreateInstance_Ok()
var instance = ObjectExtensions.CreateInstance<MockComplexObject>(false);
Assert.NotNull(instance);
Assert.Null(instance.Test);

// 接口类型不报错
Assert.Null(ObjectExtensions.CreateInstance<MockInterface>(true));
}

private interface MockInterface
{
string? Name { get; set; }
}

private class MockComplexObject
Expand Down
Loading