gpt4 book ai didi

c# - 用于常见操作的 C# 属性的有序列表?

转载 作者:太空宇宙 更新时间:2023-11-03 14:21:16 25 4
gpt4 key购买 nike

背景:我有一个具有 7 个属性的表单 ViewModel,每个 ViewModel 代表向导的各个部分,并且都实现了 IFormSection。我正在尝试为多部分 AJAX 客户端和单部分禁用 JavaScript 的客户端之间的这些 ViewModel 使用单一定义(即 DRY/SPoT)。

重要的是让这些属性作为属性进行访问,以便自动序列化/反序列化工作(即 ASP.NET MVC 模型绑定(bind)),并且这些属性还必须可以单独为 null 以指示未提交的部分。

但我也有 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; }
}

我遇到了无法使用抽象静态方法的问题,导致太多的反射调用或泛型来做愚蠢的事情,还有其他问题只会让我的整个思考过程变得糟糕。

帮忙吗?

附注我承认我可能忽略了一个涉及委托(delegate)或其他东西的更简单的设计。我也意识到我这里有 SoC 问题,并非所有问题都是为 StackOverflow 总结问题的结果。

最佳答案

如果顺序不变,您可以让属性或方法返回 IEnumerable<object> ;然后 yield 返回每个属性值...或 IEnumerable<Tuple<string,object>> ...您可以稍后对其进行迭代。

一些 super 简单的东西,比如:

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)));
}

关于c# - 用于常见操作的 C# 属性的有序列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5319184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com