简体   繁体   中英

How do I set value of a class' private member's public field via Reflection?

I have a C# class that looks like:

public class MyClass { 
  private Member member; 

  public MyClass() { 
    member = new Member(); 
  }

  //.. other properties and methods here. 
}

public class Member { 
    public String property1 { get; set; } 
    public bool isSet { get; set; } 
    // other things to do. 
}

Now, normally I want Member to be exposed, like this:

public class MyClass { 
  public Member member; 

  public Member Property { 
       get { return this.member; } 
       set { this.member = value; } 
  }

}

to get it done and over with. However, in the actual implementation, exposing Member object would be a security risk and is something that is usable only internally by MyClass' processing. My team prefers that it is hidden out of use and not publicly consumable. Given that, I was looking through Reflection on how to do it. I was going to be using the SetValue() to make a MyClassExtension, to make a cleaner implementation, but I get InvalidOperationExceptions about accessing/modifying fields.

Can someone help?

You can use BindingFlags to access non-public members:

var v = new MyClass();

var memberField = v.GetType().GetField("member",
        BindingFlags.NonPublic | BindingFlags.Instance);

var member = memberField.GetValue(v);

// no flags necessary for a public property
var property1Property = member.GetType().GetProperty("property1");  

property1Property.SetValue(member,"test");

Although be aware that if exposing Member is a security risk, then accessing it through reflection is just as risky - in fact more so, because any errors won't show up until run-time.

It would be better to know exactly what you're trying to accomplish - there may be another way that doesn't involve reflection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM