How can I get the default value of a field in a cl

2019-07-04 04:21发布

Say I have my class, and I have the non-static variable

int x = 5;

After the code runs x is changed to something else, how can I get the value x started with using reflection?

标签: c# reflection
3条回答
劫难
2楼-- · 2019-07-04 04:31

if i understand you correctly you want the initial value of the x. for that you need another member or parameter to keep the first initializing of x. for example in your class:

int FirstX = -1;// or any other value you know ain't gonna come
bool firstInitial = true;

public int X
{
   set
   {
      if(firstInitial)
      {
        FirstX = value;
        firstInitial = false;
      }

      x = value
   }
}
查看更多
戒情不戒烟
3楼-- · 2019-07-04 04:40

Now if you mean default value that is set at class level, you already know as it is constant other way would be creating an instance of the class for which you need default value.

ClassName className= new ClassName();
className.MyProp//This will always give default value.

new ClassName().MyProp //would also do.

If you want list of transactional values you need to implement it, reflection is not meant for that.

查看更多
迷人小祖宗
4楼-- · 2019-07-04 04:50

Short answer: you can't.

If you implement some kind of custom transactional system, than it is possible. Out of the box: no luck.

And yes, the custom transactional system can be very simple: add another field or property that you use to 'remember' the initial value.

查看更多
登录 后发表回答