简体   繁体   English

访问超出装配范围的内部属性

[英]Accessing internal property out of the assembly scope

I have class with internal property: 我有内部属性类:

internal virtual StateEnum EnrolmentState  
{
    get { ..getter logic }
    set { ..setter logic }
}

However I want to be able to access to this property outside of the assembly so I created method that simply returns this property: 但是,我希望能够在程序集外部访问此属性,因此我创建了只返回此属性的方法:

public StateEnum GetCurrentState()
{
    return EnrolmentState;
}

But when I call this method from class outside of this assembly I get an exception 但是,当我从该程序集之外的类中调用此方法时,出现异常

(System.TypeLoadException: Method 'get_EnrolmentState' on type 'EnrolmentAopProxy' from assembly '44fe776f-458e-4c5d-aa35-08c55501dd43, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is overriding a method that is not visible from that assembly.)

So it is possible to access to internal member outside of the assembly in any way, or I should consider a different approach. 因此可以以任何方式访问程序集外部的内部成员,或者我应该考虑采用其他方法。

Just to mention that this class is used as an O/R mapper entity (NPersist) and it is overrided from the O/R mapper to inject persistence code. 只需提及,该类用作O / R映射器实体(NPersist),并且从O / R映射器中重写以注入持久性代码。

Why is the property internal in the first place? 为什么首先是内部财产? If you want to have public access to it, make it public. 如果要公开访问它,请将其公开。 I assume you have some control over this, as otherwise you wouldn't be able to add a public method to access it in the first place. 我假设您对此具有一定的控制权,否则您将无法添加公共方法来首先访问它。

If you only want selected other assemblies to be able to access it, InternalsVisibleTo is your friend (pun not intended) - but as Erik says, you should think about the design carefully at that point. 如果您只希望选定的其他程序集能够访问它,则InternalsVisibleTo是您的朋友(双关语)-但正如Erik所说,您应该在此时仔细考虑设计。

As to why you're getting that particular error - it looks like your AOP proxy is still trying to override the internal property, rather than using your public method. 至于为什么会收到该特定错误-看来您的AOP代理仍在尝试覆盖内部属性,而不是使用public方法。 It's hard to know whether or not you can change that without knowing more about your particular setup - but making the property public is likely to be a simpler fix. 在不了解特定设置的情况下很难知道是否可以更改此设置,但是将属性公开是一种更简单的解决方法。

This sounds like you should reconsider your choice of design. 听起来您应该重新考虑设计的选择。 Internal is used to avoid what you are trying to do, so consider using some kind of public access to the properties instead. 使用Internal可以避免尝试做的事情,因此请考虑使用对属性的某种公共访问。

It's possible to use the InternalsVisibleTo Attribute to make a specific assembly able to reach internal properties but from my point of view that's a poor design. 可以使用InternalsVisibleTo属性使特定的程序集能够达到内部属性,但是从我的角度来看,这是一个糟糕的设计。

Yes I agree that this is weird design. 是的,我同意这是奇怪的设计。 I will go with protected modifier since InternalVisibleTo attribute doesn't works for me. 我将使用protected修饰符,因为InternalVisibleTo属性对我不起作用。

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

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