当匿名类型属性是函数参数时,我想在函数内部创建一个匿名类型。
例如,对于函数: 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/