【发布时间】:2011-04-29 19:49:35
【问题描述】:
当匿名类型属性是函数参数时,我想在函数内部创建一个匿名类型。
例如,对于函数: 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;
}
【问题讨论】:
-
你想创建一个已知字段名和类型的匿名类型,为什么需要反射? new { FirstName = FirstName, ... } 可以吗?
-
他希望在运行时定义 - 我相信。
-
@Aliostad - 但描述只是说明 值 应该来自参数,参数/属性的名称已经存在...
-
你为什么要这样做?这样做很难,因为这可能是个坏主意。
标签: c# reflection types anonymous