我不会做,真的。属性应该由构造函数明确地初始化,这就是它们存在的原因。不要忘记初始化字段。
但我不知道为什么你需要它,所以这里是一些代码。
可靠地设置任何属性(包括私有属性)并不容易。通常我做这样的(从我的头,我会检查我的真正的代码明天):
var properties = this.GetType().Properties(
BindingFlags.Instance
| BidningFlags.NonPublic
| BindingFlags.Public);
foreach(PropertyInfo property in properties)
{
// if a property is declared on a base type with a private setter,
// get the definition again from the declaring type,
// unless you can't call the setter.
// Probably it is even more reliable to get the properties setter
// from the declaring type.
if (property.DeclaringType != this)
{
property = property.DeclaringType.GetProperty(
property.PropertyName,
BindingFlags.Instance
| BidningFlags.NonPublic
| BindingFlags.Public);
}
if (property.CanWrite)
{
// assumed that you define a dictionary having the default values.
property.SetValue(this, defaultValues[property.PropertyType];
}
}
为什么你想这样做?你的答案极大地影响了答案。 – Gabe 2010-10-04 20:54:15
我有一个类应该都具有相同的默认值的许多属性,但在阅读了回应并思考它之后,再一次在构造函数的一个属性中设置默认值会更清晰。 – etoisarobot 2010-10-05 13:27:24