【发布时间】:2016-09-17 17:27:57
【问题描述】:
我想根据现有对象和白名单动态创建匿名对象。
例如我有以下课程:
class Person
{
string FirstName;
string LastName;
int Age;
}
现在我已经创建了一个函数 FilterObject 来根据 whitelist 参数创建一个新的匿名 obj,如下所示:
public static class Filter
{
public static object FilterObject(Person input, string[] whitelist)
{
var obj = new {};
foreach (string propName in whitelist)
if (input.GetType().GetProperty(propName) != null)
// Pseudo-code:
obj.[propName] = input.[propName];
return obj;
}
}
// Create the object:
var newObj = Filter.FilterObject(
new Person("John", "Smith", 25),
new[] {"FirstName", "Age"});
结果应该如下所示。我想将此对象用于我的 Web API。
var newObj = new
{
FirstName = "John",
Age = 25
};
有什么办法可以做到吗?
【问题讨论】:
标签: c# .net types properties casting