我正在寻找对我用于动态表单应用程序的模式的优化。
我有一个带有方法的存储库类:
public Entity Find(string objectId, List<string> includedProperties);
这将返回一个实体对象,仅包含“includedProperties”中指定的字段,因为在这种情况下为所有目的构建整个对象是不必要的开销(一些实体有数百个属性)。
使用此存储库的示例域代码通常如下所示:
var includedProperties = new List<string> {
"FirstChildName" ,
"FirstChildDob",
"SecondChildName",
"SecondChildDob"
}
然后我获取一个对象:
var person = repository.Find("123",includedProperties);
然后我将属性与 GetProperty(string propertyName)
一起使用方法:
var firstChildDob = person.GetProperty("FirstChildDob").AsDateTime();
...etc
这一切都很好,并且非常适合应用程序的动态设计。然而,令我恼火的是,在获取对象之前,我总是需要单独声明一个“已用”属性列表。
因此,我的问题是,通过反射或其他一些巧妙的方法,我能否通过查看稍后在代码中使用“GetProperty”方法传递的参数来简化“包含的属性”的构建?强>
使用上面的示例,我想使用像这样(或类似)的助手来构建列表:
var includedProperties = HelperObject.GetFieldsUsedInCurrentCodeFile();
这会以某种方式获取传递给“GetProperty()”方法的字符串常量,从而省去显式声明的需要。欢迎提出任何建议!
最佳答案
其实我前一段时间也遇到过类似的问题;当时我能想到的最好办法是定义一个枚举,其中包含我想在方法中使用的属性的名称。
使用这种方法,您可以通过遍历枚举来构建包含属性的列表。
与字符串相比,这种方法有几个好处:
任何属性拼写问题或属性名称更改都在一个位置进行。
如果您使用的是 Resharper 等工具,您可以确定枚举中何时有未使用的“属性”。
例如:
private enum PersonMethodProperties
{
FirstChildName,
FirstChildDob,
SecondChildName,
SecondChildDob
}
private void PersonMethod()
{
var includedProperties = GetIncludePropertiesFromEnum(typeof(PersonMethodProperties));
var person = repository.Find("123", includedProperties);
var firstChildDob = person.GetProperty(PersonMethodProperties.FirstChildDob.ToString()).AsDateTime();
}
private List<string> GetIncludePropertiesFromEnum(Type propertiesEnumType)
{
var includedProperties = new List<string>();
foreach (var name in Enum.GetNames(propertiesEnumType))
{
includedProperties.Add(name);
}
return includedProperties;
}
关于c# - 在使用属性之前动态查找使用过的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20914971/