在使用它们之前动态查找使用过的属性

Pau*_*haw 6 c# reflection

我正在寻找我用于动态表单应用程序的模式的优化.

我有一个带有方法的存储库类:

public Entity Find(string objectId, List<string> includedProperties);
Run Code Online (Sandbox Code Playgroud)

这将返回一个Entity对象,只包含"includedProperties"中指定的字段,因为在这种情况下为所有目的构建整个对象是不必要的开销(某些实体具有数百个属性).

使用此存储库的示例域代码通常如下所示:

var includedProperties = new List<string> {
    "FirstChildName" , 
    "FirstChildDob",
    "SecondChildName",
    "SecondChildDob"
}
Run Code Online (Sandbox Code Playgroud)

然后我获取一个对象:

var person = repository.Find("123",includedProperties);
Run Code Online (Sandbox Code Playgroud)

然后我用一个GetProperty(string propertyName)方法使用Properties :

var firstChildDob = person.GetProperty("FirstChildDob").AsDateTime();
...etc
Run Code Online (Sandbox Code Playgroud)

这一切都很好,并且非常适合应用程序的动态设计.但是,我发现在获取对象之前,我总是需要单独声明一个"used"属性列表,这令人恼火.

所以,我的问题是,通过反思或其他一些聪明,我可以通过查看稍后在代码中使用"GetProperty"方法传递哪些参数来简化"包含属性"的构建吗?

使用上面的例子,我想使用像这样(或类似)的帮助器来构建列表:

var includedProperties = HelperObject.GetFieldsUsedInCurrentCodeFile();
Run Code Online (Sandbox Code Playgroud)

这将以某种方式拾取传递给"GetProperty()"方法的字符串常量,从而节省了显式声明的需要.欢迎任何建议!

com*_*ech 2

其实我不久前也遇到过类似的问题;当时我能想到的最好办法是定义一个枚举,其中包含我想在该方法中使用的属性的名称。

使用这种方法,您可以通过循环枚举来构建包含的属性列表。

与字符串相比,这种方法有几个好处:

  1. 任何属性拼写问题或属性名称更改都可以在一个位置进行。

  2. 如果您使用的是 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;
    }
Run Code Online (Sandbox Code Playgroud)