c# - 从反射 ParamInfo[] 创建匿名类型

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

最佳答案

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

事实上,类型对您是匿名的,但对 CLR 不是。如果您查看 ildasm.exe 或反射器中的程序集,您会看到这些名称奇怪的匿名类型始终具有 <>。在他们的名字里。

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

关于c# - 从反射 ParamInfo[] 创建匿名类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4008268/

相关文章:

javascript - 在 typescript 中键入具有最大属性数的动态键

c# - 如何从 C# 打印到 Bluebird BIP-1300 热敏打印机?

c# - 如何使用 C# 获取 Azure 容器虚拟文件夹中的文件

c# - 存储 html css javascript 的最佳数据类型

c# - 枚举字符串属性时出现 TargetParameterCountException

java - 通用 OR 而不是 AND <T extends Number |字符序列>

scala - 为什么我可以在 Scala 中连接 String 和 Int?

c# - mono 是否支持带有preserveObjectReferences 标志的DataContractSerializer?

c# - 按类型或字符串类型强类型 Azure 移动服务表对象?

.net - 委托(delegate)返回类型的问题