c# - 在使用属性之前动态查找使用过的属性

标签 c# reflection

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

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

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()”方法的字符串常量,从而省去显式声明的需要。欢迎提出任何建议!

最佳答案

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

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

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

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

关于c# - 在使用属性之前动态查找使用过的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20914971/

相关文章:

c# - 如何在 VC++ 中为软件创建一个 c# 包装器?

c# - .NET DICOM库

c# - 使用 C++ 2008 Redistributables 的 VS2010 安装项目?

c# - C# 中的“向后”公钥/私钥加密,我该怎么做?

function - 如何获取 Azure FunctionApp 绑定(bind)的返回绑定(bind)属性

java - 为什么 java.lang.reflect.Modifier 有一个公共(public)构造函数?

c# - IPAddress.GetAddressBytes() 方法 - 什么字节顺序?

c# - 当参数之一是动态时,如何获取类型的构造函数?

java - 如何迭代java类并使用hashmap来选择正确的方法?

java - 使用 Class.forName 实例化参数化类型