我需要在两个相似的对象(C#)之间进行绑定:
public class TypeA
{
public int I;
public string S;
}
public class TypeB
{
public IntField I;
public StringField S;
}
当TypeA中的字段发生更改时,我需要更新TypeB中的匹配字段。
IntField是一个具有int类型的Value字段的对象,因此更新TypeB可以写成:
bInstance.I.Value = aInstance.I;
如果我理解正确,如果我使用INotifyPropertyChanged将TypeB绑定到TypeA,它将导致样板:
aInstance.PropertyChanged += (sender, args) =>
{
if (args.PropertyName == "I")
this.I.Value = sender.I;
if (args.PropertyName == "S")
this.S.Value = sender.S;
};
此外:
编辑:
IntField是一个类。 它用于系统中存在的另一种数据绑定(复杂,整个系统依赖于此)。它继承自表示一般可绑定字段的类。这是其中的一部分:
public class IntField : GeneralField
{
private int _value;
public int Value
{
get { return _value; }
set
{
IsDirty = true;
_value = value;
}
}
// ... a couple of abstract method implementations go here (setting _value, and getting value in a non-type specific way)
}
答案 0 :(得分:1)
如果你不想要大量的手动编码,基于反射或基于元编程的东西将是你最好的选择。例如:
static void Entwine(INotifyPropertyChanged source, object target)
{
source.PropertyChanged += (sender,args) =>
{
var prop = target.GetType().GetProperty(args.PropertyName);
if(prop != null)
{
var field = prop.GetValue(target) as GeneralField;
if(field != null)
{
var newVal = source.GetType().GetProperty(args.PropertyName)
.GetValue(source);
field.SetValue(newVal); // <=== some method on GeneralField
}
}
};
}
在很多情况下,这样会很好,但如果反映真的有问题,那么像FastMember这样的工具可以提供帮助:
static void Entwine(INotifyPropertyChanged source, object target)
{
var sourceAccessor = ObjectAccessor.Create(source);
var targetAccessor = ObjectAccessor.Create(target);
source.PropertyChanged += (sender, args) =>
{
var field = targetAccessor[args.PropertyName] as GeneralField;
if (field != null)
{
var newVal = sourceAccessor[args.PropertyName];
field.SetValue(newVal);
}
};
}
这比反射快得多 - 它使用了很多技巧来避免疼痛。这只需要像:
abstract class GeneralField
{
// ...
public abstract void SetValue(object value);
}
class Int32Field : GeneralField
{
// ...
public override void SetValue(object value)
{
Value = (int)value;
}
}
当然还有INotifyPropertyChanged
实施,例如:
public class TypeA : INotifyPropertyChanged
{
private int i;
private string s;
public int I
{
get { return i; }
set { SetField(ref i, value); }
}
public string S
{
get { return s; }
set { SetField(ref s, value); }
}
private void SetField<T>(ref T field, T value,
[CallerMemberName]string propertyName = null)
{
if (!EqualityComparer<T>.Default.Equals(field, value))
{
field = value;
var handler = PropertyChanged;
if (handler != null) handler(
this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}