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

Rod*_*iko 7 c# reflection types anonymous

我想在函数内部创建一个匿名类型,当匿名类型属性是函数参数时.

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

我将有一个匿名类型的属性:FirstName,LasName,年龄和身高.并且函数参数的值将是匿名类型属性的值.

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;
    }
Run Code Online (Sandbox Code Playgroud)

Ali*_*tad 3

如果我理解正确并且您想在运行时定义属性,这是不可能的。尽管在匿名类型中,您可以创建自己定义的类型,然后通过赋值,但属性的名称必须在编译时已知。

事实上,该类型对您来说是匿名的,但对 CLR 来说却不是。如果您查看 ildasm.exe 或 Reflector 中的程序集,您将看到这些匿名类型的名称中始终包含奇怪的名称<>

C# 的动态特性可能会在这里有所帮助,但据我所知,它们有助于我们没有类型信息的对象进行通信,而不是创建对象 - 但可能有一种我不知道的方法。