无法访问C#静态类

时间:2014-11-11 22:32:49

标签: c# dynamic-loading

我无法实现我在这里得到的答案!,任何人都可以帮我访问这个私有静态类吗?

namespace VEParameterTool
{
    class ProcessorPlugIn
    {
        private static class UnsafeNativeMethods
        {
            [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi)]
            static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)]string lpFileName);

            [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
            static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

            [DllImport("kernel32", SetLastError = true)]
            static extern bool FreeLibrary(IntPtr hModule);
        }      

        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        private delegate ErrorCode ProcessorFunction(ref IntPtr pRx);

        IntPtr hLib = UnsafeNativeMethods.LoadLibrary("Processor.dll");
    }
}

当我尝试LoadLibrary时,我收到有关保护级别的错误:

'VEParameterTool.ProcessorPlugIn.UnsafeNativeMethods.LoadLibrary(string)' is inaccessible due to its protection level

我已经搜索了解决方案,但无法看到与静态类有关的任何内容。

任何人都会非常感激。

安迪

2 个答案:

答案 0 :(得分:3)

为什么要尝试声明私有静态类?我能想到的唯一能够访问类中信息的方法是,如果要使用公共方法将其设置为嵌套的私有静态类 - 并且基于发布的代码并非如此。

私有意味着 - 它无法从外部访问。在此处详细了解访问修饰符:http://msdn.microsoft.com/en-us/library/ms173121.aspx

请参阅此处以获取私有静态类实现的示例:

https://dotnetfiddle.net/Lyjlbr

using System;

public class Program
{
    public static void Main()
    {
        Bar.DoStuff();

        // Bar.DoOtherStuff(); // Cannot be done due to protection level

        Bar.DoStuffAndOtherStuff(); // note that this public static method calls a private static method from the inner class
    }

    private static class Bar
    {
        public static void DoStuff()
        {
            Console.WriteLine("Test");
        }

        public static void DoStuffAndOtherStuff()
        {
            DoStuff();
            DoOtherStuff();
        }

        private static void DoOtherStuff()
        {
            Console.WriteLine("other stuff");
        }
    }
}
编辑:显然你也可以使用反射访问私有类/成员/函数,但我不太了解它。见这里:Why can reflection access protected/private member of class in C#?

答案 1 :(得分:2)

您可以离开内部班级private,只允许ProcessorPlugIn班级访问,但您必须制作方法public

private static class UnsafeNativeMethods
{
    [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi)]
    public static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)]string lpFileName);

    [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
    public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

    [DllImport("kernel32", SetLastError = true)]
    public static extern bool FreeLibrary(IntPtr hModule);
}

这些方法只能从可以访问其包含类的位置访问,在此示例中为ProcessorPlugIn