我有一个类型(人类),我想知道我能不能做System.Activator.CreateInstance(Of Human)().所以基本上我想检查Human是否有一个公共无参数构造函数/或带有可选参数的公共构造函数,这些参数可以在New Human不给出任何参数的情况下调用.
是否有可能事先检查是否System.Activator.CreateInstance(Of T)会失败?(我的意思是除了将语句包装System.Activator.CreateInstance(Of Human)()在Try Catch中当然...)
我试过这个,但它不起作用:
Option Strict On : Option Explicit On
Module Test
Public Class Human
Public Sub New(Optional ByVal a As Integer = 1)
End Sub
End Class
Public Sub Main()
Dim c = GetType(Human).GetConstructor(System.Type.EmptyTypes)
MsgBox(c Is Nothing)
End Sub
End Module
Run Code Online (Sandbox Code Playgroud)
要检查构造函数是否为空或所有参数都是可选的:
var hasEmptyOrDefaultConstr =
typeof(Human).GetConstructor(Type.EmptyTypes) != null ||
typeof(Human).GetConstructors(BindingFlags.Instance | BindingFlags.Public)
.Any (x => x.GetParameters().All (p => p.IsOptional));
Run Code Online (Sandbox Code Playgroud)