简体   繁体   English

如何通过反射设置班级私人成员的公共领域的价值?

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

I have a C# class that looks like: 我有一个C#类,看起来像:

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. 但是,在实际的实现中,暴露Member对象将带来安全风险,并且只能在MyClass的处理内部使用。 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. 我将使用SetValue()创建MyClassExtension,以实现更简洁的实现,但我收到有关访问/修改字段的InvalidOperationExceptions。

Can someone help? 有人可以帮忙吗?

You can use BindingFlags to access non-public members: 您可以使用BindingFlags访问非公共成员:

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. 尽管要知道,如果暴露Member是安全隐患,那么通过反射访问它也同样有风险-事实上,风险更大,因为任何错误直到运行时才会出现。

It would be better to know exactly what you're trying to accomplish - there may be another way that doesn't involve reflection. 最好确切地知道您要完成的工作-可能有另一种方式不涉及反思。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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