7

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

例如,对于函数: 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;
    }
4

2 回答 2

3

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

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

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

于 2010-10-24T13:07:11.263 回答
0

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

于 2011-01-31T14:51:52.493 回答