[英]Reflection for Constructors
Here: 这里:
defaultCon
binds itself to Dog()
Constructor defaultCon
将自身绑定到Dog()
构造函数
legCon
binds itself to Dog(int legs)
Constructor legCon
将自身绑定到Dog(int legs)
构造函数
Why do we specify 我们为什么要指定
new Type[0]
in Line X even though there are no parameters in Default Constructor 即使默认构造函数中没有参数,第X行中的new Type[0]
(new[] { typeof(int) })
in Line Y ! (new[] { typeof(int) })
在Y行中! Curly braces inside argument/parameter field.Similar problem in Line Z. 参数/参数字段中的花括号。Z行中的类似问题。
I searched on StackOverflow - this answer came close but doesn't answer my question. 我在StackOverflow上搜索- 这个答案接近了,但没有回答我的问题。 Here is my code: 这是我的代码:
namespace Coding
{
internal class Dog
{
public int NumberOfLegs { get; set; }
public Dog()
{
NumberOfLegs = 4;
}
public Dog(int legs)
{
NumberOfLegs = legs;
}
}
public class Class1
{
static void Main(string[] args)
{
/*line X*/ var defaultCon = typeof(Dog).GetConstructor(new Type[0]); // Get Default Constructor without any params
/*line Y*/ var legCon = typeof(Dog).GetConstructor(new[] { typeof(int) });//get constructor with param int
var defaultDog = defaultCon.Invoke(null) as Dog;//invoke defaultCon for a Dog Object
/*Line Z*/ var legDog = legCon.Invoke(new object[] { 5 });//invoke legCon for a Dog object(Sets number of legs as 5) as Dog
Console.Read();
}
}
}
Why do we specify "new Type[0]" in Line X even though there are no parameters in Default Constructor 为什么即使在默认构造函数中没有参数,我们也还是在X行中指定“ new Type [0]”
To say that there are no parameters - so the array of parameter types is empty. 要说没有参数-因此参数类型的数组为空。
Why do we specify "(new[] { typeof(int) })" in Line Y! 为什么我们在Y行中指定“(new [] {typeof(int)})”! Curly braces inside argument/parameter field. 参数/参数字段内的花括号。
To create an array or parameter types with a single element - the type corresponding to int
. 用单个元素创建数组或参数类型-对应于int
的类型。
Similar problem in Line Z. Z行中的类似问题。
Same answer, except this time you're creating an array of arguments, instead of parameter types. 答案相同,只是这次您要创建一个参数数组,而不是参数类型。
The simplest overload of Type.GetConstructor
still takes an array of types to indicate the parameters of the constructor you're trying to get. Type.GetConstructor
的最简单重载仍然采用类型数组来指示您要获取的构造函数的参数。
The value Type[0]
is an empty array , which indicates no parameters. 值Type[0]
是一个空数组 ,表示没有参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.