[英]Is there a way to know if object property value is already set or is it default?
I am looking for a way to find out if object property value is already set or if it's still default.我正在寻找一种方法来确定 object 属性值是否已设置或是否仍为默认值。 My class:
我的class:
class TestModel
{
public string TestStringProperty { get; set; }
public int TestIntProperty { get; set; }
public bool TestBoolProperty { get; set; }
}
and I initialize it:我初始化它:
TestModel model = new()
{
TestBoolProperty = false,
TestStringProperty = "testValue",
TestIntProperty = 1,
};
Later I run this code, to get current and default values for those properties:稍后我运行这段代码,以获取这些属性的当前值和默认值:
foreach (PropertyInfo propertyInfo in model.GetType().GetProperties())
{
object? currentValue = model.GetType()?.GetProperty(propertyInfo.Name)?.GetValue(model, null);
object? defaultValue = propertyInfo.GetValue(Activator.CreateInstance(dummyModel.GetType()), null);
Trace.WriteLine($"Current value for property {propertyInfo.Name} is: {currentValue?.ToString()}");
Trace.WriteLine($"Default value for property {propertyInfo.Name} is: {defaultValue?.ToString()}");
}
and the output is: output 是:
Current value for property TestStringProperty is: testValue
Default value for property TestStringProperty is:
Current value for property TestIntProperty is: 1
Default value for property TestIntProperty is: 0
Current value for property TestBoolProperty is: False
Default value for property TestBoolProperty is: False
However, TestBoolProperty (bool) value is the same as default value (false).但是,TestBoolProperty (bool) 值与默认值 (false) 相同。 If I hadn't initialized it, it would still be default.
如果我没有初始化它,它仍然是默认的。
My question: Is there a way to find out if this property is set, even if its value the same as default?我的问题:有没有办法查明是否设置了此属性,即使它的值与默认值相同?
Use backing fields and a boolean value:使用支持字段和 boolean 值:
class TestModel
{
private string _testStringProperty;
private bool _testStringPropertySet;
public string TestStringProperty
{
get { return _testStringProperty; }
set { _testStringProperty = value; _testStringPropertySet = true; }
}
Then you can check the boolean field in addition to the property value.那么除了属性值,还可以查看boolean字段。
As far as I know there's no way to tell the difference between a default value and an assigned value if that value is the same as the default.据我所知,如果默认值与默认值相同,则无法区分默认值和分配值。 @DiplomacyNotWar provided a way around that.
@DiplomacyNotWar 提供了一种解决方法。 Another option is to use
Nullable
and check the HasValue
property.另一种选择是使用
Nullable
并检查HasValue
属性。 This will be null
until the field is set (or if it was set to null
explicitly).这将是
null
,直到该字段被设置(或者如果它被显式设置为null
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.