【发布时间】:2010-10-11 14:32:41
【问题描述】:
我正在尝试创建一个类以用作其他对象中的字段,该类可以保存临时未保存的值,直到在对象上调用 SaveChanges 方法,以便我可以将值传递给存储的过程,这将使用新值更新所有非空字段,并将空字段保留为其原始值。
我希望能够做到这一点:
private Field<int> MyInt;
private Field<int?> MyNullableInt;
private Field<string> MyString;
然后可以像这样使用 Field 对象:
MyInt = new Field<int>(1); // initialise with a value
MyInt.Value = 2; // assign a new value internally marking it as having a new value
int x = MyInt.Value; // read the current value
int? newInt = MyInt.NewValue; // read the newly set value, or null if there is no new value
我希望能够创建以下字段:
- 在 db 中具有 NOT NULL 约束的值类型,例如 int、bool 等。
- 值类型,例如 int?、bool? 等,允许在 db 中使用 NULL。
- 总是可以为空的引用类型,例如字符串。
我仍在学习泛型,但我开始了解它们,但是,我有点坚持这一点,因为我可以根据需要创建一个 Field 对象,该对象与不可为空的类型一起使用,或者可以为空的类型,但不能两者兼有。
这是我迄今为止想出的:
protected class Field<T> where T : struct {
private T _Field;
private bool _IsNew;
public Field(T InitialValue) {
_Field = InitialValue;
_IsNew = false;
}
public T Value {
get { return _Field; }
set {
if (!_Field.Equals(value)) {
_Field = value;
_IsNew = true;
}
}
}
public Nullable<T> NewValue {
get {
if (_IsNew) {
_IsNew = false;
return _Field;
}
return null;
}
}
public bool IsNew { get { return _IsNew; } }
}
这很好用。我还可以将类型约束更改为where T : class,并在NewValue 方法上将Nullable<T> 更改为T,这使它适用于可为空的类型,但我如何让它适用于所有数据类型?我真的需要创建两个不同的类来处理这两种不同的场景吗?
谢谢, 本
【问题讨论】:
-
这是一个附注,但请将您的字段和变量小写。