我有十几个继承自同一个基类的类。对于每个类,我想在属性更新时更改状态,因此我有一个名为UpdateProperty(oldValue,newValue)的函数。我正在寻找一种方法来使这些通用,所以当我添加一个新类时,我不必添加新的功能。 这就是我所拥有的:
public TicketType UpdateProperty(TicketType oldValue, TicketType newValue)
{
if (oldValue != newValue && ObjectState != ObjectState.New && ObjectState != ObjectState.Deleted)
{
ObjectState = ObjectState.Changed;
}
return newValue;
}
public Layout UpdateProperty(Layout oldValue, Layout newValue)
{
if (oldValue != newValue && ObjectState != ObjectState.New && ObjectState != ObjectState.Deleted)
{
ObjectState = ObjectState.Changed;
}
return newValue;
}
public Division UpdateProperty(Division oldValue, Division newValue)
{
if (oldValue != newValue && ObjectState != ObjectState.New && ObjectState != ObjectState.Deleted)
{
ObjectState = ObjectState.Changed;
}
return newValue;
}
public MasterDataList UpdateProperty(MasterDataList oldValue, MasterDataList newValue)
{
if (oldValue != newValue && ObjectState != ObjectState.New && ObjectState != ObjectState.Deleted)
{
ObjectState = ObjectState.Changed;
}
return newValue;
}
public MasterDataListItem UpdateProperty(MasterDataListItem oldValue, MasterDataListItem newValue)
{
if (oldValue != newValue && ObjectState != ObjectState.New && ObjectState != ObjectState.Deleted)
{
ObjectState = ObjectState.Changed;
}
return newValue;
}
public Ticket UpdateProperty(Ticket oldValue, Ticket newValue)
{
if (oldValue != newValue && ObjectState != ObjectState.New && ObjectState != ObjectState.Deleted)
{
ObjectState = ObjectState.Changed;
}
return newValue;
}
正如你所看到的,他们都是这样做的。有人能指出我正确的方向吗?
答案 0 :(得分:2)
是的,但您必须制作通用方法。如果需要,可以将它放在基类中:
public T UpdateProperty<T>(T oldValue, T newValue)
{
if (!object.Equals(oldValue, newValue) && this.ObjectState != ObjectState.New && this.ObjectState != ObjectState.Deleted)
{
this.ObjectState = ObjectState.Changed;
}
return newValue;
}
答案 1 :(得分:0)
我不仅要设置ObjectState,还要设置方法内的属性值。
将方法放在基类中。
public abstract class BaseClass
{
public ObjectState ObjectState { get; private set; }
protected bool Set<T>( ref T field, T value )
{
if Equals( field, value ) return false;
field = value;
if ( ObjectState == ObjectState.Unchanged )
ObjectState = ObjectState.Changed;
return true;
}
}
并在你继承的课程中
public class Foo : BaseClass
{
private TicketType _ticketType;
public TicketType TicketType
{
get => _ticketType;
set => Set( ref _ticketType, value );
}
}