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

时间:2010-10-24 12:50:28

标签: c# reflection types anonymous

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

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

我将拥有一个具有以下属性的匿名类型:FirstName,LasName,Age和height。 并且函数参数的值将是匿名类型属性的值。

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

2 个答案:

答案 0 :(得分:3)

如果我理解正确并且您想在运行时定义属性,则无法实现。虽然在匿名类型中您可以创建在那里定义的类型,然后通过分配值,但必须在编译时中知道属性的名称。

事实上,该类型对您来说是匿名的,但对于CLR则不是。如果你在ildasm.exe或反射器中查看程序集,你会看到这些匿名类型的名字总是名字中有<>

C#的动态可能会在这里提供帮助但据我所知,他们帮助对象进行通信,这些对象是我们没有类型信息,而不是创建 - 但可能有一个我不知道的方式。

答案 1 :(得分:0)

你能否使用“Linq to DataSet”Field<T>(String Name)设计模式?实际上为什么不只是使用DataTable。编译器不需要知道该字段是否存在,只需要知道类型安全的类型。这样做的一个原因是实现某种类型的解析器来生成过滤器,或者动态配置字段名称。