[英]Ordered list of C# properties, for common operations?
背景:我有一个具有7个属性的ViewModel表单,每个ViewModel代表向导的各个部分,并且都实现IFormSection。 我正在尝试在多节AJAX客户端和禁用了单节JavaScript的客户端之间为这些ViewModel使用单一定义(即DRY / SPoT)。
将这些属性作为属性进行访问很重要,这样自动序列化/反序列化才能工作(即ASP.NET MVC模型绑定),并且这些属性也必须可以单独为空以指示未提交的部分。
但是我也有6-10次使用常见的IFormSection操作来遍历这些可序列化的属性,在某些情况下是有序的。 那么如何存储此属性列表以供重用? 编辑:这包括批处理new()
在满负荷操作中将它们注册起来。
例如,最终结果可能类似于:
interface IFormSection {
void Load();
void Save();
bool Validate();
IFormSection GetNextSection(); // It's ok if this has to be done via ISectionManager
string DisplayName; // e.g. "Contact Information"
string AssociatedViewModelName; // e.g. "ContactInformation"
}
interface ISectionManager {
void LoadAllSections(); // EDIT: added this to clarify a desired use.
IFormSection GetRequestedSection(string name); // Users can navigate to a specific section
List<IFormSection> GetSections(bool? ValidityFilter = null);
// I'd use the above List to get the first invalid section
// (since a new user cannot proceed past an invalid section),
// also to get a list of sections to call .Save on,
// also to .Load and render all sections.
}
interface IFormTopLevel {
// Bindable properties
IFormSection ProfileContactInformation { get; set; }
IFormSection Page2 { get; set; }
IFormSection Page3 { get; set; }
IFormSection Page4 { get; set; }
IFormSection Page5 { get; set; }
IFormSection Page6 { get; set; }
IFormSection Page7 { get; set; }
}
我遇到了无法使用抽象静态方法的问题,导致太多的反射调用或泛型无法执行愚蠢的事情,以及其他问题,这些问题使我的整个思维过程变得难闻。
救命?
ps我接受,我可能忽略了一个涉及委托人之类的简单得多的设计。 我也意识到我这里有SoC问题,并非所有问题都是归结于StackOverflow问题的结果。
如果顺序是常数,则可以具有返回IEnumerable<object>
的属性或方法; 然后yield返回每个属性值...或IEnumerable<Tuple<string,object>>
...,您可以稍后对其进行迭代。
超级简单的东西,例如:
private IEnumerable<Tuple<string,object>> GetProps1()
{
yield return Tuple.Create("Property1", Property1);
yield return Tuple.Create("Property2", Property2);
yield return Tuple.Create("Property3", Property3);
}
如果您想要更通用的方法来做同样的事情,则可以使用反射:
private IEnumerable<Tuple<string,object>> GetProps2(){
var properties = this.GetType().GetProperties();
return properties.Select(p=>Tuple.Create(p.Name, p.GetValue(this, null)));
}
或者,idk? 扩展方法吗?
private static IEnumerable<Tuple<string,object>> GetProps3(this object obj){
var properties = obj.GetType().GetProperties();
return properties.Select(p=>Tuple.Create(p.Name, p.GetValue(obj, null)));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.