[C#]使用Reflection檢查指定類別是否含有預設建構子
namespace ConsoleApplication17 { class Program { static void Main(string[] args) { Console.WriteLine(HasDefaultConstructor1<TestClass1>()); Console.WriteLine(HasDefaultConstructor2<TestClass1>());
Console.WriteLine(HasDefaultConstructor1<TestClass2>());
Console.WriteLine(HasDefaultConstructor2<TestClass2>());
}
private static Boolean HasDefaultConstructor1<T>()
{
var type = typeof (T);
foreach (var c in type.GetConstructors(BindingFlags.Instance | BindingFlags.Public))
{
if (c.GetParameters().Length ==0)
return true;
}
return false;
}
private static Boolean HasDefaultConstructor2<T>()
{
var type = typeof (T);
return type.GetConstructor(Type.EmptyTypes) != null;
}
}
internal class TestClass1
{
public TestClass1()
{
}
public TestClass1(int arg1)
{
}
}
internal class TestClass2
{
public TestClass2(int arg1)
{
}
}
}