如何在通用对象上设置任意数量的属性?
我希望能够调用一个方法来创建对象并根据传递到该方法中的参数设置该对象的属性。参数的数量是任意的,但问题是我不想使用字符串。我想像在 lambda 表达式中那样使用实际属性。
我希望能够使用如下所示的内容来调用该方法:
controller.Create<Person>(f=>{f.Name = 'John', f.Age = 30})
或者使用实际的属性引用 (f.Name) 而不是属性的字符串表示形式。
另一个规定是我不希望在方法调用之前完成任何工作。我正在库中编写此内容,因此我不希望用户必须执行任何操作,除了进行调用并获取属性设置为传入值的对象之外。
I want to be able to call a method that creates an object and sets properties of the object based on the parameters passed into the method. The number of parameters is arbitrary, but the catch is I don't want to use strings. I want to use the actual properties sort of like you do in lambda expressions.
I want to be able to call the method with something that might look like this:
controller.Create<Person>(f=>{f.Name = 'John', f.Age = 30})
or something along those lines where I use the actual property reference (f.Name) instead of a string representation of the property.
Another stipulation is that I don't want any work to be done before the method call. I'm writing this in a library, so I don't want the user to have to do anything except make the call and get back an object with the properties set to the values passed in.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以执行以下操作:
create 方法签名将是:
其中 T : class
在这里不是严格要求的,但如果T
是值类型,则对其属性的修改将迷路了。You can do something like:
The create method signature will be:
where T : class
is not strictly required here but ifT
is a value type, the modifications to its properties would be lost.