简体   繁体   English

从反射ParamInfo []创建一个匿名类型

[英]Create an anonymous type from reflection ParamInfo[]

i want to create an anonymous type inside a function, when the anonymous type properties are the function parameters. 我想在函数内部创建一个匿名类型,当匿名类型属性是函数参数时。

for example, for the function: private bool CreatePerson(string FirstName, string LasName, int Age, int height); 例如,对于函数:private bool CreatePerson(string FirstName,string LasName,int Age,int height);

i will have an anonymous type with the properties: FirstName,LasName,Age and height. 我将有一个匿名类型的属性:FirstName,LasName,年龄和身高。 and the values of the function parameters will be the values of the anonymous type properties. 并且函数参数的值将是匿名类型属性的值。

private bool CreatePerson(string FirstName, string LasName, int Age, int height)
    {
        // Get this method parameters
        MethodBase currentMethod =  MethodBase.GetCurrentMethod();
        ParameterInfo[] parametersInfo = currentMethod.GetParameters();

        // create an object of the parameters from the function.
        foreach (ParameterInfo paramInfo in parametersInfo)
        {
            // add a property with the name of the parameter to an anonymous object and insert its value to the property.
            // WHAT DO I DO HERE?
            ....
        }

        return true;
    }

If I understood correctly and you want to define the properties at runtime, this is not possible. 如果我理解正确并且您想在运行时定义属性,则无法实现。 Although in anonymous types you may be able to create types that you define there and then by assigning values, the name of the properties must be known at compile time . 虽然在匿名类型中您可以创建在那里定义的类型,然后通过分配值,但必须在编译时知道属性的名称。

In fact, the type is anonymous to you but not to the CLR . 事实上, 这种类型对你来说是匿名的,但对于CLR则不是 If you look at the assembly in ildasm.exe or reflector, you will see these anonymous types with strange names always having <> in their names. 如果您查看ildasm.exe或反射器中的程序集,您将看到这些匿名类型,其名称中的名称始终为<>

C#'s dynamic might be able to help here but as far as I know, they help with communicating with objects that are that we do not have type information for, not creating - but there might be a way that I do not know. C#的动态可能会在这里提供帮助,但据我所知,它们有助于与我们没有类型信息的对象进行通信 ,而不是创建 - 但可能有一种我不知道的方式。

Could you not use the "Linq to DataSet" Field<T>(String Name) design pattern? 你能否使用“Linq to DataSet” Field<T>(String Name)设计模式? In fact why not just use a DataTable. 实际上为什么不只是使用DataTable。 The compiler does not need to know that the field exists, only what type it is to be type safe. 编译器不需要知道该字段是否存在,只需要知道类型安全的类型。 One reason to do this would be to implement some type of parser to generate filters, or to configure field names dynamically. 这样做的一个原因是实现某种类型的解析器来生成过滤器,或动态配置字段名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM