我正在嘗試在 C# 中動態設置泛型對象中的原始類型的值//Create a new instance of the value object (VO)var valueObject = Activator.CreateInstance<T>();//Get the properties of the VOvar props = valueObject.GetType().GetProperties();//Loop through each property of the VOforeach (var prop in props){ if (prop.GetType().IsPrimitive) { var propertyType = prop.PropertyType; var value = default(propertyType); prop.SetValue(prop, value); }}問題是我不能propertyType用作獲取默認值的類型。我如何獲得propertyType可以使用的類型default()?
1 回答

MMTTMM
TA貢獻1869條經驗 獲得超4個贊
您應該將實例傳遞給 SetValue:
prop.SetValue(valueObject, value);
如果要設置默認值,可以使用:
var propertyType = prop.PropertyType;
var defaultValue = Activator.CreateInstance(propertyType);
prop.SetValue(valueObject, defaultValue);
- 1 回答
- 0 關注
- 177 瀏覽
添加回答
舉報
0/150
提交
取消