我正在创建自己的UI绑定系统,该系统将控件绑定到关联对象。什么比使用一系列if语句更好?如果我添加新控件来提供新的跟踪项,我不希望每次都更新这一系列的if语句。
TimelineTrackControl control;
Type objectType = track.GetType();
if (objectType == typeof(ShotTrack))
{
control = new ShotTrackControl();
}
else if (objectType == typeof(AudioTrack))
{
control = new AudioTrackControl();
}
else if (objectType == typeof(GlobalItemTrack))
{
control = new GlobalItemTrackControl();
}
else
{
control = new TimelineTrackControl();
}
control.TargetTrack = track;
timelineTrackMap.Add(track, control);
答案 0 :(得分:1)
您可以使用反射,在这种情况下http://msdn.microsoft.com/en-us/library/vstudio/d133hta4就像这样:
Activator.CreateInstance(null, track.GetType().toString() + "Control");
答案 1 :(得分:1)
你可以:
创建一个包含曲目类型和相应控件类型的Dictionary<Type, Type>
:
private static readonly Dictionary<Type, Type> ControlTypes = new Dictionary<Type, Type>
{
{ typeof(ShotTrack), typeof(ShotTrackControl) },
...
};
获得相应的控制:
control = Activator.CreateInstance(ControlTypes[track.GetType()]);
创建一个包含曲目类型和相应控件创建者的Dictionary<Type, Func<Control>>
:
private static readonly Dictionary<Type, Func<Control>> ControlTypes = new Dictionary<Type, Func<Control>>
{
{ typeof(ShotTrack), () => new ShotTrackControl() },
...
};
要创建新的相应控件:
control = ControlTypes[track.GetType()]();
定义存储相应控件类型的自定义属性:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class TrackControlAttribute : Attribute
{
public readonly Type ControlType;
public TrackControlAttribute(Type controlType)
{
ControlType = controlType;
}
}
[TrackControl(typeof(ShotTrackControl))]
public class ShotTrack
{
...
}
要创建新的相应控件:
object[] attrs = track.GetType().GetCustomAttributes(typeof(TrackControlAttribute), true);
if (attrs.Length != 0);
control = Activator.CreateInstance(((TrackControlAttribute)attrs[0]).ControlType);
修改强>
在第3个选项中修复了错误。