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

2019-07-04 04:24发布

问题:

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?

回答1:

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.



回答2:

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:

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.



标签: c# reflection