Access to internal classes from another project

二次信任 提交于 2019-12-19 05:42:27

问题


I'm wondering if it's possible to access internal class variables from other project in c#. I know that is impossible in regular use, I explain it below.

I have one project (P1 [class library]) containing those classes...

internal class Settings
{
    public static long size {get;set;}

    public static DoSomethingInternalOnly()
    {
    }
}

public class Program
{
    public static Main()
    {

    }
}

... and another one (P2) containing:

public class Program
{
    public static Main()
    {
        //P1.CopyOfSettings.size = 2048; ???
    }
}

In Settings class I store internal variables (and methods) for app which cannot be visible from other projects. But those settings need to be passed somehow from P2 to P1 so I need second class "Settings2" in P2 containing the same variables (variables only!) as "Settings" with public keyword.

I feel that creating several classes containing the same variables is a waste of time and makes code unreadable. Is there better way to accomplish this?


回答1:


You can use the InternalsVisibleTo attribute and provide the name of a specific assembly that can see the internal types in your assembly.

That being said.. I think you are bordering on over-designing this. If the Settings class belongs only to Assembly A... don't put it in Assembly B... put it in Assembly A.




回答2:


Yes it is, using InternalsVisibleTo, but I would only recommend doing this for Unit Test projects.

Otherwise, you should extract a common interface, make it public and put it in a separate assembly that can be references by both projects.

You could make all the properties of the interface read-only so that the consumer cannot change them.




回答3:


I think this is what you are looking for:

http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx




回答4:


That is the point of internal modifier - to not allow this. Either change it to public or use some kind of proxy class to expose the functionality you need to the outer world.



来源:https://stackoverflow.com/questions/21527332/access-to-internal-classes-from-another-project

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!