常用操作的C#属性的有序列表?

时间:2011-03-15 23:13:28

标签: c# asp.net-mvc properties model

背景:我有一个包含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; }
}

我遇到了一些问题,我无法使用抽象的静态方法,导致过多的反射调用或泛型来做愚蠢的事情,以及其他问题只会让我的整个思维过程闻起来很糟糕。

帮助?

P.S。 我接受我可能会忽略一个涉及代表或其他东西的简单设计。我也意识到我在这里遇到SoC问题,并非所有问题都是对StackOverflow问题进行总结的结果。

1 个答案:

答案 0 :(得分:1)

如果订单是常量,您可以拥有返回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)));
}