用反射就可以了。下面是一個例子:
using System;
using System.Reflection;
class People
...{
public string Name;
public int Age;
public People()
...{
Name = "Unknow Person";
Age = -1;
}
public override string ToString()
...{
return string.Format("Name:{0}, Age:{1}", Name, Age);
}
public void CallConstructor()
...{
ConstructorInfo constructor = this.GetType().GetConstructor(
BindingFlags.Instance | BindingFlags.Public,
;null,
new Type[0],
null
);
constructor.Invoke(this, null);
}
}
class Program
...{
static void Main(string[] args)
...{
People p = new People();
p.Age = 100;
p.Name = "Old man";
Console.WriteLine(p);
p.CallConstructor();
Console.WriteLine(p);
}
}
只是要注意,反射性能比較差。
技術討論的QQ群: 2514097 或 10987609