Skip to content

Commit 1d734ec

Browse files
committed
fix bug: ValueType CreateInstance
1 parent 20dcfaa commit 1d734ec

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

src/SourceGeneration.Reflection/SourceReflector.cs

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@ public static T CreateInstance<
2828
#endif
2929
T>(params object?[] args)
3030
{
31+
if (typeof(T).IsValueType && (args == null || args.Length == 0))
32+
{
33+
return default!;
34+
}
35+
3136
return (T)CreateInstance(GetRequiredType<T>(), args);
3237
}
3338

@@ -50,10 +55,27 @@ public static object CreateInstance(
5055
{
5156
args ??= [];
5257

53-
var methods = typeInfo.DeclaredConstructors.Where(x => x.Parameters.Count(x => !x.HasDefaultValue) <= args.Length).ToList();
58+
if (typeInfo.Type.IsValueType)
59+
{
60+
if (typeInfo.IsReflected)
61+
{
62+
return Activator.CreateInstance(typeInfo.Type, args)!;
63+
}
64+
65+
if (args.Length == 0)
66+
{
67+
var ctor = typeInfo.DeclaredConstructors.FirstOrDefault(x => x.Parameters.Length == 0 && x.Accessibility == SourceAccessibility.Public);
68+
if (ctor != null)
69+
{
70+
return ctor.Invoke(args)!;
71+
}
72+
}
73+
}
5474

55-
var method = Type.DefaultBinder.BindToMethod(ReflectionExtensions.DeclaredOnlyLookup, methods.Select(x => x.ConstructorInfo).ToArray(), ref args, null, null, null, out object? state);
5675

76+
77+
var methods = typeInfo.DeclaredConstructors.Where(x => x.Parameters.Count(x => !x.HasDefaultValue) <= args.Length).ToList();
78+
var method = Type.DefaultBinder.BindToMethod(ReflectionExtensions.DeclaredOnlyLookup, methods.Select(x => x.ConstructorInfo).ToArray(), ref args, null, null, null, out _);
5779
if (typeInfo.IsReflected)
5880
{
5981
return method.Invoke(null, args)!;
@@ -114,10 +136,7 @@ public static SourceTypeInfo? GetType<
114136

115137
if (allowRuntimeReflection)
116138
{
117-
if (allowRuntimeReflection)
118-
{
119-
return _reflectionTypes.GetOrAdd(type, CreateSourceTypeInfo);
120-
}
139+
return _reflectionTypes.GetOrAdd(type, CreateSourceTypeInfo);
121140
}
122141
return null;
123142
}

0 commit comments

Comments
 (0)