开发者

is there a better way to do this without reflection?

I need to set all of the properties of a class usi开发者_开发知识库ng the same function. Currently I am using reflection to get all of the properties and looping through to set their values. I know all of the properties, there is nothing dynamic happening.

Here is my code I am currently running in my constructor:

foreach (PropertyInfo property in this.GetType().GetProperties())
{
    // retreive the value and set it
    property.SetValue(this, GetValue(field), null);
}

Is there way to do something similar without using reflection?


Not that I am aware of based on the information given here.

That said, it does beg the question what are you doing that would require you to do this? Why do you need to iterate over all your properties in a loop anyway, how many do you have?

A bit more detail may prompt someone to give you a better solution. For example, what are the properties doing? Are they connected to some underlying data that could be changed without using reflection? Is having a bunch of discrete properties the way to go if you have a lot of them?


Um, maybe I'm misinterpreting what you are saying, but you said you know all the properties, why not just write a method to set them?

void SetValues() {
    this.Property1 = field1;
    this.Property2 = field2;
    this.Property3 = field3;
    this.Property4 = field4;
}

I suspect there is something missing from your question.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜